liveBook · Manning

Dict.get

As explained in Python Workout, Second Edition

dict.get is the dictionary method that returns the value associated with a key or a specified default when the key is absent.

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

How Python Workout, Second Edition covers it

How deep it goes
Works through default retrieval in accumulation and dictionary comparison, while deferring broader input validation details.
Examples
Uses rainfall totals, paired dictionary differences, missing keys, and defaultdict accumulation as concrete applications.
What it assumes
Assumes familiarity with dictionaries and teaches default retrieval through counting, user data, and comparison exercises.
What you can do after
Apply it via Python dictionary lookups, defaulted counters, rainfall accumulation, and missing-key comparisons.
How it connects
Connects dictionary retrieval with dictionaries, sets, input conversion, and defaultdict-based accumulation.

Also explained in

Compare how 5 books explain dict.get →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.