liveBook · Manning

Dict.get

As explained in Python Workout: 50 ten-minute exercises

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

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

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Shows defaulted lookup in accumulation and dictionary diffing, but does not develop the method beyond these patterns.
Examples
Uses rainfall accumulation and a dictdiff function comparing shared, changed, and absent keys.
What it assumes
Assumes working knowledge of dictionaries, keys, values, assignment, arithmetic, and basic input conversion.
What you can do after
Apply dict.get to retrieve optional values, supply defaults, accumulate counts, and compare dictionaries without KeyError.
How it connects
Links dictionary lookup with sets, KeyError avoidance, input conversion, and defaultdict.

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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.