Use dict.get when a lookup should return a value if a key exists or a chosen default when it does not. This avoids a missing-key failure and keeps lookup logic compact. section 5.20
A useful pattern combines retrieval with updating: rainfall.get(city_name, 0) returns the existing total or starts at zero. Convert numeric input before adding it. section 5.9
Accumulate rainfall by city
rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain The first entry for a city uses 0; later entries retrieve and extend its existing total. section 5.9
Apply the same lookup strategy when comparing dictionaries:
- Combine both dictionaries’ keys into a set, then use first.get(key) and second.get(key) to retrieve values or None for absent keys; record differences in the result. section 5.13
- Do not add raw input strings when numeric totals are intended: input returns strings, so convert with int or float and handle invalid values when needed. section 5.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
Inspect the complete accumulation pattern, including integer conversion, invalid-input handling, the default zero, and dictionary assignment. section 5.9




