get, in, and Friends

Sometimes a key may not be in the dictionary. A few dictionary methods, and the in operator, help you handle this safely.

OperationWhat it does
get(key, fallback)Reads a value, and does not fail when the key is missing
pop(key, fallback)Removes a key and returns its value
items()Gives you all the key-value pairs
scores = {"Mira": 8, "Noah": 6}

print(scores.get("Zoe", 0))
print("Mira" in scores)
print(scores.pop("Noah", 0))
print(len(scores))

Output:

0
True
6
1

The fallback is the value you get back when the key is missing. "Zoe" is not a key, so get returns the fallback 0. You do not get a KeyError. The in operator checks whether a key exists, and gives True or False.

pop removes a key and returns its value. Here it removes "Noah" and returns 6, so only one pair is left. You can also give pop a fallback, for the case when the key is missing.

Choose a fallback that makes sense for your program. For a missing count, zero is a good choice.

In the exercise, look up two products safely and check whether one of them exists.