When a dictionary may not contain a key, dict.get retrieves its value without raising KeyError. Supply a default to receive that value when the key is absent; without one, the result is None. section 4.14 section 4.23
Use dict.get to make common dictionary operations shorter and more direct:
- Compare dictionaries by retrieving each key from both dictionaries, using None when a key is missing. section 4.14
- Accumulate a value with a default: rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain. section 4.9
- Prefer this direct lookup-and-default pattern to separately checking for a key, retrieving its value, and handling KeyError. section 4.14
Accumulating rainfall
rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain initializes a city at zero, then adds later measurements. Convert input to int or float first, because raw input is a string. section 4.9
try:
mm_rain = int(input('Enter mm rain: '))
except ValueError:
print('You didn't enter a valid integer; try again.')
continue
rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain
See the complete input-validation and rainfall-accumulation listing, including ValueError handling and the dict.get default. section 4.9




