Sub topic 5
Dictionaries: looking things up by key
This chapter assumes you know basic Python syntax (variables, loops, functions) and the built-in types int, str, and bool. It also assumes you have read the earlier chapters on mutability and hashability. The code needs Python 3.9 or later because it uses the | operator on dicts.
The working model
A dictionary (dict) maps keys to values. You give it a key and it returns the associated value, without scanning through the other entries. This is the main reason to choose a dict over a list of pairs. A list of pairs has to be searched one entry at a time. A dict goes almost directly to the entry.
Three properties define the type:
- Keys are unique. Assigning to an existing key replaces its value.
- Keys must be hashable, which is why a tuple of numbers works as a key and a list does not.
- Since Python 3.7, a dict remembers insertion order. Iterating over it yields entries in the order the keys were first added.
Values have no restrictions. They can be any object, including other dicts and lists.
Creating and reading
The most common ways to build a dict are a literal, the dict() constructor, and a comprehension.
users = {"ana": 31, "ben": 27}
also_users = dict(ana=31, ben=27) # keyword form, keys must be valid names
from_pairs = dict([("ana", 31), ("ben", 27)])
print(users == also_users == from_pairs) # True
squares = {n: n * n for n in range(4)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9}Reading and writing use square brackets. in tests for a key, not a value.
users = {"ana": 31, "ben": 27}
print(users["ana"]) # 31
print(users.get("cy", 0)) # 0, because the key is missing and a default is given
users["cy"] = 45
print("cy" in users) # True
print(31 in users) # False, because `in` checks keys
print(31 in users.values()) # True, but this scans every valueThe last line shows an asymmetry. Searching by key is fast. Searching by value is a linear scan, as slow as searching a list. If you often need to go from value to key, build a second dict that maps the other way.
Missing keys
Reading a missing key with [] raises KeyError. There are three ways to deal with that. Pick the one that matches your intent.
users = {"ana": 31, "ben": 27}
try:
users["zed"]
except KeyError as e:
print("missing:", e) # missing: 'zed'
print(users.get("zed")) # None
print(users.get("zed", 0)) # 0Use [] when a missing key is a bug and you want the program to fail loudly. Use .get() when absence is normal and you have a sensible fallback.
.get() has one trap. It cannot tell "the key is missing" from "the key is present and its value is None".
settings = {"timeout": None}
print(settings.get("timeout", 30)) # None, not 30, because the key exists
print("timeout" in settings) # TrueIf None is a legitimate stored value, test with in first, or use a unique sentinel object as the default.
setdefault(key, default) is a related method. It returns the existing value if the key is present. Otherwise it inserts the default and returns it. That makes it useful for grouping:
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = {}
for w in words:
groups.setdefault(w[0], []).append(w)
print(groups)
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}The default expression is evaluated on every call, even when the key already exists. Here that means a new empty list is built and thrown away each time. For a hot loop, collections.defaultdict (covered in the last chapter) avoids that cost.
Updating and deleting
inventory = {"apples": 5, "pears": 2}
inventory.update({"pears": 4, "plums": 9}) # overwrite or add several keys
print(inventory) # {'apples': 5, 'pears': 4, 'plums': 9}
removed = inventory.pop("apples") # remove and return the value
print(removed) # 5
print(inventory.pop("kiwi", None)) # None, no KeyError because a default is given
del inventory["plums"] # remove, raises KeyError if missing
print(inventory) # {'pears': 4}pop with a default is the safe removal. del is stricter and fails on a missing key.
To combine dicts without changing either, use |. When both sides have a key, the right-hand value wins.
defaults = {"color": "red", "size": 1}
overrides = {"size": 3}
merged = defaults | overrides
print(merged) # {'color': 'red', 'size': 3}
print(defaults) # {'color': 'red', 'size': 1}, unchanged
defaults |= overrides # in-place version, same effect as defaults.update(overrides)
print(defaults) # {'color': 'red', 'size': 3}On older Python versions, {**defaults, **overrides} does the same job as |.
Iterating
Looping over a dict gives its keys. Three methods give you other views:
d.keys()for keysd.values()for valuesd.items()for(key, value)tuples, which you normally unpack in the loop header
prices = {"tea": 3, "coffee": 4}
for name in prices:
print(name) # tea, then coffee
for name, price in prices.items():
print(name, price) # tea 3, then coffee 4
doubled = {name: price * 2 for name, price in prices.items()}
print(doubled) # {'tea': 6, 'coffee': 8}
cheap = {name: p for name, p in prices.items() if p < 4}
print(cheap) # {'tea': 3}These views are live. If the dict changes, the view reflects it. They are not copies.
Do not change the size while iterating
Adding or removing keys during a loop over the same dict raises RuntimeError.
d = {"a": 1, "b": 2}
try:
for k in d:
d[k + "x"] = 0
except RuntimeError as e:
print(e) # dictionary changed size during iteration
# Safe: iterate over a snapshot of the keys
for k in list(d):
if d[k] == 0:
del d[k]
print(d) # {'a': 1, 'b': 2}Changing the value of a key that already exists is fine, because the size does not change.
Order and equality
Insertion order is preserved, but it does not affect equality. Two dicts with the same pairs are equal in any order.
a = {"x": 1, "y": 2}
b = {"y": 2, "x": 1}
print(a == b) # True
print(list(a), list(b)) # ['x', 'y'] ['y', 'x']Updating an existing key keeps its original position. Deleting a key and adding it again moves it to the end.
Which keys are allowed
A key must be hashable: it needs a hash value that never changes during its lifetime, and it must compare equal to other keys with the same hash when they represent the same thing. Strings, numbers, bool, None, tuples of hashable items, and frozensets qualify. Lists, dicts, and sets do not.
locations = {(1, 2): "tuple key works"}
print(locations[(1, 2)])
try:
locations[[1, 2]] = "list key fails"
except TypeError as e:
print(e) # unhashable type: 'list'A tuple is hashable only if everything inside it is. (1, [2, 3]) fails as a key, because hashing it requires hashing the list.
Keys are matched by hash and equality, not by type. Numbers that compare equal are the same key:
d = {1: "int"}
d[1.0] = "float"
d[True] = "bool"
print(d) # {1: 'bool'}The dict keeps the first key object (1) and replaces only the value. This surprises people who use a mix of numbers and booleans as keys.
For your own classes, defining __eq__ without __hash__ makes instances unhashable. If you define both, the hash must not change when the fields used by __eq__ change. Otherwise the dict will look in the wrong place and lose the entry.
Common patterns
Counting
text = "a b a c b a"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts) # {'a': 3, 'b': 2, 'c': 1}collections.Counter does this in one call, and it is covered in the last chapter.
Lookup tables instead of if/elif chains
A dict can replace a long chain of comparisons, and it can hold functions as values.
def add(a, b):
return a + b
def sub(a, b):
return a - b
operations = {"+": add, "-": sub}
def calculate(op, a, b):
try:
func = operations[op]
except KeyError:
raise ValueError(f"unknown operator: {op}") from None
return func(a, b)
print(calculate("+", 2, 3)) # 5
print(calculate("-", 2, 3)) # -1Nested data and shared values
Dict values are references. A shallow copy made with .copy() or dict(d) makes a new dict but shares the value objects.
a = {"tags": ["x"]}
b = a.copy()
b["tags"].append("y")
print(a) # {'tags': ['x', 'y']}, the list is sharedUse copy.deepcopy when you need independent nested values.
How a lookup works internally
A dict is a hash table. Looking up a key follows these steps:
Several consequences follow from this model:
- Average lookup, insert, and delete take constant time, regardless of dict size. The cost does not grow with the number of entries.
- Two different keys can land in the same slot, which is a collision. Python resolves it by probing other slots. In the worst case, with many collisions, operations degrade toward linear time. This is rare with built-in types.
- The hash is computed once per lookup, and for strings it is cached. A key whose
__hash__is slow makes every lookup slow. - When the table fills up, Python allocates a larger one and reinserts everything. Most inserts are cheap, and an occasional insert is expensive.
- A dict uses more memory than a list of the same length. You pay memory for speed of lookup.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `KeyError: 'x'` | Read a missing key with `[]` | Use `.get()`, or check `in` first, or fix the bug that made the key absent |
| `TypeError: unhashable type: 'list'` | Used a list, set, or dict as a key | Convert to a tuple or frozenset |
| `RuntimeError: dictionary changed size during iteration` | Added or removed keys in a loop over the same dict | Loop over `list(d)` or build a new dict |
| `.get()` returns `None` for a key that exists | The stored value is `None` | Test with `in`, or use a sentinel default |
| Edit to a copy changes the original | `.copy()` is shallow | Use `copy.deepcopy` for nested values |
| `1`, `1.0`, and `True` collapse into one key | They are equal and have equal hashes | Do not mix them as keys |
Exercises
Exercise
You run config = {"retries": 0} and then value = config.get("retries") or 3. You expected value to be 0, but it is 3. Why does this happen, and what is a correct way to write the line?
Show answer
The value 0 is falsy, so or discards it and picks 3. The key exists, so .get() is not the problem. Write value = config.get("retries", 3), which uses 3 only when the key is missing. If None can also be stored, use value = config["retries"] if "retries" in config else 3.
Exercise
Given stock = {"a": 0, "b": 5, "c": 0}, write code that removes every key whose value is 0 without raising a RuntimeError, and state what stock contains afterwards.
Show answer
Build a new dict with a comprehension: stock = {k: v for k, v in stock.items() if v != 0}. Alternatively, loop over a snapshot with for k in list(stock): if stock[k] == 0: del stock[k]. Afterwards stock is {'b': 5}. Looping over stock directly while deleting would raise "dictionary changed size during iteration".
Exercise
A dict maps product IDs to names, and you often need to find the ID for a given name. Why is name in products.values() a poor choice, and what would you do instead?
Show answer
.values() has no index, so the in test scans every value, which takes time proportional to the number of products. Build a second dict that maps names to IDs, for example ids_by_name = {name: pid for pid, name in products.items()}, and look names up there. This works only if names are unique. If they are not, map each name to a list of IDs.