Python dict() Function

Returns a dictionary from a comma separated list of key-value pairs.

Syntax

Python
dict()
dict(mapping)
dict(iterable)
dict(**kwargs)

Parameters

ParameterDescription
mapping Optional. A mapping of key / values pairs that will be used to initialise the dictionary.
iterable Optional. An iterable with each item of the form (key, value). The dictionary will be initialised using dict[key] = value.
kwargs Optional. A set of name=value pairs in the argument list. For example dict(a=1, b=2).

Example: An empty dictionary

Python
# Create an empty dictionary
d = dict()
print(d)

Output

{}

Example: Create a dictionary from a set of key=value arguments

Python
d = dict(firstName = 'John', lastName = 'Doe')
print(d)

Output

{'firstName': 'John', 'lastName': 'Doe'}

Notes

While firstName = 'John' looks like a variable assignment, it is not — the key cannot be accessed like a variable.

Example

Python
# Create a dictionary from an initialization list.
d = dict(firstName = 'John', lastName = 'Doe')
print(d)
print(firstName)

Output

{'firstName': 'John', 'lastName': 'Doe'}
Traceback (most recent call last):
  File "dict.py", line 4, in <module>
    print(firstName)
NameError: name 'firstName' is not defined
</module>