← All lessons

Accessing a dictionary: get

Sign in · Sign up

Lesson 5.10

If the key is missing, ages["Leo"] fails with a KeyError. The get method does not raise an error in that situation:

ages = {"Mia": 14, "Timur": 15}

print(ages.get("Mia"))                  # 14
print(ages.get("Leo"))                  # None
print(ages.get("Leo", "no data"))       # no data

The second argument is the default value; it comes back only if the key is missing. If the key is there, get returns the real value and the default is not used.

The dictionary ages, the name who and the default value fallback are set by the check. Print, in order:

  1. the age with get;
  2. the age with get and the default value.
Hint

.get(key) returns None if the key is missing — with no error.

The second argument of .get(key, value) is a fallback answer instead of None. Compare: square brackets fail, .get does not.