Sub topic 4
Missing keys and default values
This chapter assumes you can write Python loops and functions, know what a dictionary is, and have seen the counting and grouping patterns from the previous chapter. Here we look at what happens when you ask a map for a key it does not hold, and the main ways to handle that case.
What happens when a key is missing
Indexing a dict with [] raises KeyError if the key is absent. This is deliberate. A missing key often signals a bug, and an error that stops the program is better than a silent wrong answer.
prices = {"apple": 3, "pear": 4}
try:
print(prices["plum"])
except KeyError as e:
print("missing:", e) # missing: 'plum'Often, though, a missing key is a normal case. A word you have not counted yet is a good example. You then need to choose what "missing" means for your code.
Four ways to handle it
| Approach | Behavior on a missing key | Changes the map? |
|---|---|---|
| `d[k]` | Raises `KeyError` | No |
| `d.get(k, default)` | Returns `default` | No |
| `d.setdefault(k, default)` | Inserts `default`, then returns the stored value | Yes |
| `defaultdict(factory)` | Calls `factory()`, stores the result, returns it | Yes |
get: read without inserting
dict.get(key, default) returns the default when the key is absent and leaves the map unchanged. This makes it a good fit for counting.
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts) # {'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}If you leave out the default, get returns None. Do not use that to tell "absent" from "present with value None". Use key in d for that.
defaultdict: create values on first use
collections.defaultdict takes a factory function. When you index a missing key, it calls the factory, stores the result under that key, and returns it. This suits grouping, where each value is a list.
from collections import defaultdict
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = defaultdict(list)
for w in words:
by_letter[w[0]].append(w)
print(dict(by_letter))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}setdefault and its cost
d.setdefault(k, []) does the same job on a plain dict. It evaluates the default argument every time, even when the key exists. For a list or other object, that means building a throwaway object on each call. defaultdict avoids this, because it only calls the factory when the key is missing.
Choosing a strategy
The flow below summarizes the decision.
Common errors
- Shared mutable default.
d.get(k, [])is safe for reading. Butd.setdefault(k, shared_list)stores that same list object under every missing key, so all keys then share one list. Create a new object per key. - Wrong factory.
defaultdict([])raisesTypeError, because the argument must be callable. Passlist, not[]. - Falsy values.
d.get(k) or defaultreplaces a stored0or empty string with the default. Pass the default as the second argument togetinstead. - Silent masking. A default can hide a typo in a key name. Use defaults only where a missing key is expected.
Exercise
You loop over orders and run totals[customer] += amount on a defaultdict(int). Afterward you check if totals["Zed"] > 0: for a customer who never ordered. What does this do to the map, and how would you avoid it?
Show answer
Indexing "Zed" calls int(), which returns 0, and stores "Zed": 0 in the map, so the map grows with an entry for a customer who never ordered. The comparison itself gives False. To check without inserting, use totals.get("Zed", 0) > 0, which leaves the map unchanged.
Exercise
Why is defaultdict(list) preferred over d.setdefault(k, []) in a loop over a million items?
Show answer
setdefault builds a new empty list on every call, even when the key already exists, and then discards it. defaultdict(list) calls list() only when the key is missing.