Start learning free

LESSON 128 OF 673 · DICTIONARIES

Reading a Key That May Be Missing in Python

Lesson

TL ; DR:

d.get(key, 0) gives the key's value, or 0 when the key is missing. There is no error either way.


points = {"Ana": 7}

print(points.get("Ana", 0))   # 7
print(points.get("Ben", 0))   # 0


Full lesson:

A missing key often means "none yet". A player with no points yet has 0 points.

points["Ben"] can't say that. It stops the program with a KeyError.

get takes a key and a default. It gives the key's value when the key is there. It gives the default when it isn't.

Reading this way doesn't add the key. points still has one key afterwards.

Without a default, get gives None for a missing key.

It does what this if with in does, in one line:

score = 0
if "Ben" in points:
    score = points["Ben"]

Your task

stock counts the fruit in a shop. The code reads and prints the pears.

There are no plums yet. Read "plums" with get and 0 as the default. Store it in plums.

Then print the plums line, the same way as the pears line.

Expected output:

We have 2 pears
We have 0 plums
STEP 1 OF 2
    Ctrl + Enter to check