Sub topic 5
How default_factory really works
This chapter assumes you can use defaultdict(list) and defaultdict(int) for grouping and counting, and that you know dict lookup with [] and get(). Here you will learn what happens inside a defaultdict when a key is missing, and which mistakes follow from it.
The default_factory attribute
A defaultdict is a dict subclass with one extra attribute, default_factory. It holds the callable you passed as the first argument.
from collections import defaultdict
d = defaultdict(list)
print(d.default_factory) # <class 'list'>
d["a"].append(1)
print(d) # defaultdict(<class 'list'>, {'a': [1]})The factory is called with no arguments, and its return value becomes the value for the missing key. This is why list, int, set, and float work. Each returns an empty or zero value when called with nothing.
What happens on a lookup
The behavior lives in the __missing__ method. When d[key] does not find the key, dict calls d.__missing__(key). In defaultdict, that method does three things:
- It raises
KeyErrorifdefault_factoryisNone. - Otherwise it calls
default_factory()to build a value. - It stores the value under the key and returns it.
You can call __missing__ directly to see the insertion:
from collections import defaultdict
d = defaultdict(int)
print(d.__missing__("k")) # 0
print(d) # defaultdict(<class 'int'>, {'k': 0})Calling __missing__ by hand is only for demonstration. Normal code triggers it through d[key].
Indexing inserts, get() and in do not
Only d[key] calls __missing__. The get() method, the in operator, and pop(key, default) never do. That difference is the most common source of surprises.
from collections import defaultdict
scores = defaultdict(int)
for name in ["ann", "bob"]:
scores[name] # a bare lookup still inserts
print(len(scores)) # 2
print(scores.get("cy")) # None
print("cy" in scores) # False
print(scores.get("cy", 5)) # 5
print(len(scores)) # 2A bare lookup such as scores[name] looks like a harmless read, but it adds a key. Two consequences follow:
- Checking
if d[key]:before deciding what to do fills the dictionary with keys you only meant to test. - Iterating over
dor measuringlen(d)after reads can give larger results than you expect.
If you want to read without side effects, use key in d or d.get(key).
The factory takes no arguments
default_factory must be callable with zero arguments, or None. Passing a plain value is an error:
from collections import defaultdict
try:
defaultdict(0)
except TypeError as exc:
print(exc) # first argument must be callable or NoneTo get a constant default, wrap it in a lambda or use a named function:
from collections import defaultdict
status = defaultdict(lambda: "unknown")
print(status["job1"]) # unknown
print(dict(status)) # {'job1': 'unknown'}The factory receives no key, so it cannot build a value from the key being looked up. If you need that, subclass dict and write your own __missing__, which does receive the key:
class Upper(dict):
def __missing__(self, key):
value = key.upper()
self[key] = value # store it, as defaultdict does
return value
u = Upper()
print(u["abc"]) # ABC
print(u) # {'abc': 'ABC'}Setting default_factory to None turns a defaultdict back into something that raises KeyError on missing keys. You can also assign to the attribute later, for example d.default_factory = None, to "freeze" a dictionary once you finish building it.
Common mistakes
Returning a shared object
The factory runs once per missing key, so each key gets its own value only if the factory builds a new object each time. This version returns the same list for every key:
from collections import defaultdict
shared = []
d = defaultdict(lambda: shared)
d["a"].append(1)
print(d["b"]) # [1] both keys point at the same listWrite lambda: [] or just list instead, so each call creates a new list.
Nested defaultdicts
A factory can itself return a defaultdict. This lets you build two-level tables without checking whether the outer key exists:
from collections import defaultdict
table = defaultdict(lambda: defaultdict(int))
table["fruit"]["apple"] += 1
table["fruit"]["apple"] += 1
table["veg"]["kale"] += 1
print({k: dict(v) for k, v in table.items()})
# {'fruit': {'apple': 2}, 'veg': {'kale': 1}}The lambda is needed because defaultdict(int) is an object, not a zero-argument callable that makes a new one each time.
Expecting defaults from the constructor and copy
Keyword arguments and dictionary data passed after the factory are treated as ordinary entries. defaultdict(int, a=1) stores a with value 1, and only later missing keys use int. A copy made with d.copy() keeps the same default_factory, but it is a shallow copy, so mutable values are shared between the original and the copy.
Summary of rules
| Operation | Calls `__missing__` | Inserts key on miss |
|---|---|---|
| `d[key]` | Yes | Yes, if a factory is set |
| `d.get(key)` | No | No |
| `key in d` | No | No |
| `d.setdefault(key, v)` | No | Yes, with `v` |
Exercise
The code below runs without an error. What does it print, and why? from collections import defaultdict seen = defaultdict(list) if seen["x"]: print("found") print(len(seen), "y" in seen)
Show answer
It prints 1 False. The test seen["x"] is an index lookup, so __missing__ calls list(), stores the empty list under "x", and returns it. The empty list is falsy, so "found" is not printed, but the dictionary now has one key. The in operator never calls __missing__, so "y" is not added.