A dict (dictionary) stores key/value pairs: each unique key maps to one value, like a name to a phone number. You read a value with its key, phone["Asha"], instead of a position, and the lookup stays fast however big the dict grows.
Curly braces hold key: value pairs separated by commas; square brackets read and write single keys:
Python
person = {"name": "Ada", "born": 1815} # a dict literal
person["field"] = "math" # add a new key
print(person["name"]) # Ada
print(person.get("died", "unknown")) # unknown
print(len(person), "born" in person) # 3 True
for key, value in person.items():
print(key, "=", value)
Empty braces make a dict.
{} is an empty dict, not an empty set; write set() for an empty set. type({}) is dict.
Concept
Keys, Values, and Order
Rule
What it means
Hashable keys
Keys must be hashable: str, int, float, bool, None, frozenset, and tuples of hashable values. A list, dict, or set key raises TypeError: unhashable type.
Unique keys
Assigning to an existing key replaces its value. Equal keys are the same key, so {1: "a", True: "b"} is {1: 'b'} because True == 1.
Insertion order
Since Python 3.7 the language guarantees that a dict remembers insertion order. Printing and looping follow that order.
Updating keeps position
Assigning a new value to an existing key keeps its place. Deleting a key and adding it again puts it at the end.
Any values
Values can be anything, including lists and other dicts, and they do not have to be unique.
Mutable
A dict changes in place. Two names bound to the same dict see the same changes; use copy() for a separate dict.
Reference
Creating Dicts
Code
When to use it
{"a": 1, "b": 2}
Literal: the most common way.
dict(a=1, b=2)
Keyword arguments: keys become strings.
dict(zip(keys, values))
Pair up two parallel lists.
{n: n * n for n in nums}
Dict comprehension: compute keys and values.
dict.fromkeys(keys, 0)
Same starting value for every key.
The dict() constructor also copies another mapping, and zip() pairs keys with values. fromkeys() has its own guide.
Reference
Looping Over a Dict
Loop
What you get
for key in d:
Keys, in insertion order (same as d.keys()).
for value in d.values():
Values only.
for key, value in d.items():
Both at once, unpacked from each pair.
for key in sorted(d):
Keys in sorted order; the dict itself is unchanged.
for key in reversed(d):
Keys from newest to oldest (Python 3.8+).
keys(), values(), and items() return live views, not copies, so they always show the current contents.
Reference
Common Mistakes
Mistake
Do this instead
d["missing"] raises KeyError
Use d.get(key, default), test key in d first, or catch KeyError.
Adding or deleting keys inside for key in d:
Raises RuntimeError: dictionary changed size during iteration. Loop over list(d) or d.copy() instead. Changing values of existing keys is fine.
dict.fromkeys(keys, [])
Every key shares one list. Use {k: [] for k in keys} for separate lists.
Using a list as a key
Raises TypeError: unhashable type: 'list'. Convert it to a tuple first.
new = old to copy
Both names point to one dict. Use old.copy(), or copy.deepcopy(old) for nested data.
settings = settings.update(x)
update() returns None, so this throws the dict away. Call it on its own line.
Compare
Dict vs List vs Set
Type
Literal
Best for
Contents
Order
dict
{"a": 1}
Look up by key
Unique, hashable keys
Insertion order
list
[1, 2, 1]
Look up by position
Duplicates allowed
Position order
set
{1, 2}
Membership tests
Unique, hashable items
No guaranteed order
Code
Python Examples
Fixed data only, so the output is the same on every machine.
Example 1 — Create Dicts Four Different Ways
A literal, keyword arguments, two zipped lists, and a comprehension.
Python
literal = {"red": "#f00", "green": "#0f0"}
from_kwargs = dict(width=800, height=600)
from_pairs = dict(zip(["x", "y", "z"], [1, 2, 3]))
squares = {n: n * n for n in range(1, 5)}
print(literal)
print(from_kwargs)
print(from_pairs)
print(squares)
A dict is a built-in, mutable mapping from unique keys to values, such as {"name": "Ada", "born": 1815}. You look values up by key instead of by position.
Yes. Since Python 3.7 the language guarantees insertion order: printing and looping show keys in the order they were first added. Changing a value keeps the position.
Any hashable value: strings, numbers, booleans, None, frozensets, and tuples that contain only hashable values. Lists, dicts, and sets cannot be keys.
Use d.get(key) or d.get(key, default) for a fallback, check key in d before reading, use setdefault() to insert a default, or catch KeyError with try/except.
Use a dict when you look things up by a name or ID, such as a phone number by person. Use a list when order and position matter and items have no natural key.