dict()
Builds a dictionary from keyword arguments, from a list of key-value pairs, from two lists zipped together, or as a copy of another dictionary.
dict(**kwargs)
dict(mapping, **kwargs)
dict(iterable, **kwargs)dict() creates a dictionary: a collection that stores values under keys, like a word and its meaning. Most of the time you write a dictionary directly with curly braces, {"name": "Ana"}, but dict() is handy when the data comes in another shape.
It accepts pairs (two-item tuples or lists) and turns each pair into a key and a value. Together with zip() this makes a dictionary from a list of keys and a list of values in one line. With keyword arguments, dict(city="Oslo", zip="0150"), the names become string keys.
Since Python 3.7 a dictionary remembers the order its keys were added in. If the same key appears twice, the later value wins.
Parameters
| Parameter | What it is |
|---|---|
mapping or iterableoptional | Another dictionary to copy, or anything that gives key-value pairs, such as [("a", 1), ("b", 2)]. |
**kwargsoptional | Extra key=value pairs. The keys become strings, so they must be valid Python names. They are added last and replace earlier values with the same key. |
Return value
A new dictionary.
Examples
1Three ways to build the same dictionary
a = {"name": "Ana", "age": 34}
b = dict(name="Ana", age=34)
c = dict([("name", "Ana"), ("age", 34)])
print(a)
print(a == b == c){'name': 'Ana', 'age': 34}
True2Two lists into one dictionary
products = ["tea", "coffee", "cocoa"]
prices = [2.5, 3.2, 2.9]
menu = dict(zip(products, prices))
print(menu)
print(menu["coffee"]){'tea': 2.5, 'coffee': 3.2, 'cocoa': 2.9}
3.23Read settings from text lines
lines = ["theme=dark", "lang=en", "size=14"]
settings = dict(line.split("=") for line in lines)
print(settings)
print(int(settings["size"]) + 2){'theme': 'dark', 'lang': 'en', 'size': '14'}
16Each split("=") gives a two-item list, which dict() uses as a key and a value.
4Copy and change defaults
defaults = {"color": "blue", "size": "M", "qty": 1}
order = dict(defaults, size="L", qty=2)
print(order)
print(defaults){'color': 'blue', 'size': 'L', 'qty': 2}
{'color': 'blue', 'size': 'M', 'qty': 1}The copy gets the new values; the original stays as it was.
5Later keys win
votes = [("Lena", 3), ("Omar", 5), ("Lena", 7)]
print(dict(votes)){'Lena': 7, 'Omar': 5}Lena keeps her first position but takes the last value. To add values up instead, loop and use d[k] = d.get(k, 0) + v.
Common mistakes
Keyword keys that are not valid names
dict(first name="Ana") or dict(1="x") is a SyntaxError: with keywords, the keys must look like variable names. Use curly braces for any other key: {"first name": "Ana", 1: "x"}.
Expecting a deep copy
dict(d) copies the outer dictionary only. A list stored inside is shared by both.
team = {"name": "Blue", "members": ["Ana"]}
copy = dict(team)
copy["members"].append("Ben")
copy["name"] = "Red"
print(team){'name': 'Blue', 'members': ['Ana', 'Ben']}Questions people ask
How do I create a dictionary from two lists in Python?
dict(zip(keys, values)). Extra items in the longer list are ignored.
Is dict() or {} better?
{} is shorter and a little faster for an empty or written-out dictionary. dict() is clearer when converting pairs or copying.
How do I merge two dictionaries?
merged = a | b (Python 3.9+) or {**a, **b}. Keys in b replace the same keys in a.
Are dictionaries ordered?
Yes, since Python 3.7 they keep the order in which keys were first added.