Python 3 reference · Built-in Functions

Python dict() Function

Create a dictionary: a mapping of keys to values. Build it from keyword arguments, pairs or another mapping.

Python 3 Since 3.0

Syntax

dict(**kwargs)
dict(mapping, **kwargs)
dict(iterable, **kwargs)

Parameters

ParameterDescription
mapping / iterable optional Another mapping, or an iterable of (key, value) pairs.
**kwargs optional Extra keys given as keyword arguments.

Return value

A new dict.

Examples

Ways to build a dictionaryTry it yourself
print(dict(name="Ada", year=1815))
print(dict([("a", 1), ("b", 2)]))
print(dict(zip(["x", "y"], [10, 20])))

Output

{'name': 'Ada', 'year': 1815}
{'a': 1, 'b': 2}
{'x': 10, 'y': 20}
Merge with overridesTry it yourself
defaults = {"theme": "light", "lang": "en"}
user = {"theme": "dark"}
print(dict(defaults, **user))
print(defaults | user)  # the same, Python 3.9+

Output

{'theme': 'dark', 'lang': 'en'}
{'theme': 'dark', 'lang': 'en'}
Copy a dictionaryTry it yourself
prices = {"apple": 1.2, "pear": 0.9}
copy = dict(prices)  # a shallow copy
copy["apple"] = 2.0
print(prices["apple"], copy["apple"])

Output

1.2 2.0

Good to know

  • Dictionaries keep insertion order (guaranteed since Python 3.7).
  • dict(**kwargs) only works for keys that are valid identifiers; use {"my-key": 1} for others.
  • dict(d) is a shallow copy: nested lists and dicts are still shared.

Version history

VersionChange
Python 3.0Added
Python 3.7Insertion order is guaranteed by the language.
Python 3.9The merge operators | and |= were added.