`collections.defaultdict`: Eliminating `KeyError`
`defaultdict(factory)` calls a constructor (like `list` or `int`) whenever you access a missing key, eliminating `KeyError` crashes forever 🛡️.
from collections import defaultdict
# Auto-initializing list values:
tracker = defaultdict(list)
tracker["server1"].append(200) # No KeyError! Initializes [] on the fly!
print(dict(tracker)) # {'server1': [200]} 🚀
# 26. `collections.defaultdict`: Eliminating `KeyError` `defaultdict(factory)` calls a constructor (like `list` or `int`) whenever you access a missing key, eliminating `KeyError` crashes forever 🛡️: ```python from collections import defaultdict # Auto-initializing list values: tracker = defaultdict(list) tracker["server1"].append(200) # No KeyError! Initializes [] on the fly! print(dict(tracker)) # {'server1': [200]} 🚀 ``` Stop cluttering your algorithms with defensive boilerplate like `if key not in d: d[key] = []`. Let `defaultdict` handle missing keys cleanly at the C layer. 🧠 --- ### Question What happens when you look up a non-existent key in a `defaultdict(int)`? 🪄 - [ ] a. It automatically inserts the key mapped to `0` (default value of `int()`) without crashing - [ ] b. It crashes with an unhandled KeyError 💀 - [ ] c. It deletes the dictionary out of frustration 🗑️ - [ ] d. It converts the dictionary into an immutable tuple 🧩 --- ### Challenge Count character occurrences in `"banana"` using a `defaultdict(int)`. Increment with `counts[char] += 1` and print `counts["a"]`. 🎯 <details> <summary>Solution</summary> ```python from collections import defaultdict counts = defaultdict(int) for char in "banana": counts[char] += 1 print(counts["a"]) ``` </details>