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
| Parameter | Description |
|---|---|
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
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}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'}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
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.7 | Insertion order is guaranteed by the language. |
| Python 3.9 | The merge operators | and |= were added. |
Related
list()· Create a list: an ordered, changeable sequence. Called with an iterable, it copies its items into a new list.set()· Create a set: an unordered collection of unique items with fast membership tests and set operations.zip()· Iterate over several iterables in parallel, producing tuples of their items. Stops at the shortest unless strict=True.frozendict()· Create an immutable, hashable dictionary (new in Python 3.15). It can be a dict key or set member and can't be changed.- Python Dictionaries · tutorial