Sub topic 5
Dictionaries: looking things up by key
This chapter assumes you know Python loops and functions, and that you have read the earlier chapters on mutability and hashability. A dictionary (dict) maps keys to values. You give it a key and it returns the matching value without scanning the whole collection.
The basic operations
A dict is written with braces and key: value pairs. Square brackets read or write a value. The in operator tests whether a key exists.
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) # TrueAssigning to an existing key replaces its value. Assigning to a new key adds a pair. Reading a missing key with users["zed"] raises KeyError. The get method returns None for a missing key, or the default you pass as a second argument.
Choosing between brackets and get
Use brackets when a missing key means a bug. The KeyError then shows the problem right away. Use get when a missing key is a normal case that has a sensible fallback.
Do not use get to hide errors. If get returns None and you pass that value onward, the failure shows up later and farther from its cause.
Iterating over a dict
Looping over a dict gives its keys. Use .values() for values and .items() for key-value pairs. Since Python 3.7, a dict keeps the order in which keys were first inserted, and the language guarantees this.
users = {"ana": 31, "ben": 27}
for name, age in users.items():
print(name, age)
next_year = {name: age + 1 for name, age in users.items()}
print(next_year) # {'ana': 32, 'ben': 28}The second statement is a dict comprehension. It builds a new dict from any iterable of pairs, in the same way a list comprehension builds a list.
A worked example: counting
Counting is the most common dict task. The dict maps each item to how many times you have seen it.
text = "the cat saw the dog and the cat ran"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
# {'the': 3, 'cat': 2, 'saw': 1, 'dog': 1, 'and': 1, 'ran': 1}counts.get(word, 0) returns 0 the first time a word appears, so the first update creates the entry. Without the default, the first update would raise KeyError.
Other useful methods
| Method | What it does | Column |
|---|---|---|
| `d.setdefault(k, v)` | Returns `d[k]`. If `k` is missing, it first stores `v` under `k`. | |
| `d.pop(k, default)` | Removes `k` and returns its value, or returns `default` if `k` is missing. | |
| `d.update(other)` | Copies the pairs from `other` into `d`, overwriting duplicate keys. | |
| `d \ | other` | Returns a new dict that merges both (Python 3.9 and later). |
setdefault is useful for grouping, where each value is a list:
groups = {}
for word in ["apple", "avocado", "banana", "blueberry", "cherry"]:
groups.setdefault(word[0], []).append(word)
print(groups)
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}Common errors
- Changing a dict while looping over it. Adding or removing keys during iteration raises
RuntimeError. Build a new dict instead. - Unhashable keys. A list cannot be a key. Convert it to a tuple first.
- Assuming
d[k] = vcopiesv. The dict stores a reference. Ifvis a list, changing the list through another name also changes what the dict holds.
scores = {"a": 50, "b": 80, "c": 40}
try:
for key, value in scores.items():
if value < 60:
del scores[key]
except RuntimeError as e:
print(e) # dictionary changed size during iteration
passing = {key: value for key, value in scores.items() if value >= 60}
print(passing) # {'b': 80}The loop deletes "a" and then fails on the next step. The comprehension at the end builds the filtered dict safely. Note that scores has already lost "a" by that point, but "c" is still in it, and the comprehension filters it out.
Exercise
Given words = ["to", "be", "or", "not", "to", "be"], write code that builds a dict mapping each word to its count, then explain why counts.get(word, 0) is used instead of counts[word].
Show answer
Use counts = {} and then for word in words: counts[word] = counts.get(word, 0) + 1. The result is {'to': 2, 'be': 2, 'or': 1, 'not': 1}. Plain counts[word] would raise KeyError the first time a word is seen, because the key does not exist yet. get supplies 0 as the starting count.