Use defaultdict when repeated updates must create a missing dictionary entry automatically. It behaves like a regular dict until a missing key is requested, then calls its configured factory. section 5.9
Accumulating rainfall
from collections import defaultdict rainfall = defaultdict(int) rainfall['Boston'] += 30 rainfall['Boston'] += 30 # rainfall contains {'Boston': 60} The int factory supplies 0 for the first missing lookup, allowing += to proceed without an explicit initialization. section 5.9
from collections import defaultdict rainfall = defaultdict(int) #1 rainfall['Boston'] += 30 rainfall #2 rainfall['Boston'] += 30 rainfall #3
Inspect the executable defaultdict pattern for initializing and incrementing a rainfall mapping. section 5.9


