8. Get with default

Reading dictionary[key] fails with KeyError when the key is missing. The get() method gives you a safer option:

  • key — the key to look for.
  • default — the value returned when the key is missing. Default: None.
  • If the key exists, get() returns its value. If not, it returns default.
  • get() never adds the key to the dictionary.

Coming from JavaScript? d.get("k", fallback) is the safe read, similar to d["k"] ?? fallback. It also treats a stored None as a present value, so it does not fall back in that case.

#01

Get an existing key

Create person = {"name": "Ada"}. Print the result of person.get("name").

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Get a missing key without a default

With person = {"name": "Ada"}, print the result of person.get("age"). Without a second argument, get() returns None.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Get a missing key with a default

With person = {"name": "Ada"}, print the result of person.get("age", 0). The second argument is returned instead of None when the key is missing.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

get does not add the key

Create person = {"name": "Ada"}. Store person.get("age", 0) in a variable named age. Print age, then print person.

Print exactly:

Create a free account to save your progress and unlock chapter 2.