When several rainfall readings share a city name, a regular dictionary requires a missing-key case before adding the new value. defaultdict removes that special case by supplying a configured default. section 4.9
Two useful approaches are:
- Use rainfall.get(city_name, 0) to return the existing total or zero, then add the new measurement. section 4.9
- Use defaultdict(int), which invokes int for a missing key so += can update the total directly. section 4.9
Accumulating rainfall
from collections import defaultdict rainfall = defaultdict(int) rainfall['Boston'] += 30 rainfall['Boston'] += 30 rainfall # defaultdict(<type 'int'>, {'Boston': 60}) section 4.9
from collections import defaultdict
rainfall = defaultdict(int) #1
rainfall['Boston'] += 30
rainfall # defaultdict(<type 'int'>, {'Boston': 30})
rainfall['Boston'] += 30
rainfall # defaultdict(<type 'int'>, {'Boston': 60})
Inspect the complete REPL example showing initialization, repeated updates, and the resulting dictionary. section 4.9


