Missing Keys

Reading a key that isn't in a dictionary ends the program with a KeyError. When you aren't sure that a key is there, you have two ways to avoid the error.

The first is to ask with in, which you know from lists. With a dictionary, in looks at the keys, and the result is True or False:

contact = {"name": "Tom", "email": "tom@example.com"}

print("email" in contact)
print("phone" in contact)
print("Tom" in contact)
True
False
False

The last line is False even though Tom is in the dictionary: "Tom" is a value, not a key, and in only looks at the keys. Together with if, you read a key only when it's there:

contact = {"name": "Tom", "email": "tom@example.com"}

if "phone" in contact:
    print("Phone:", contact["phone"])
else:
    print("Tom has no phone number.")
Tom has no phone number.

The second way is the method .get(). It reads a value like the square brackets do, but when the key isn't there, the program doesn't end with an error. You get None, the value that means “nothing”, which you know from functions without return. Or you get a value of your choice, the default value, if you give it as the second argument:

contact = {"name": "Tom", "email": "tom@example.com"}

print(contact.get("email"))
print(contact.get("phone"))
print(contact.get("phone", "unknown"))
tom@example.com
None
unknown

.get() only reads: it doesn't add the key "phone" to the dictionary.

The key in square brackets (or in .get()) doesn't have to be written out in quotes. It can be in a variable. That's useful when you don't know the key while you write the program, for example in a loop:

menu = {"coffee": 45, "tea": 35}

item = "tea"
print(menu[item])
35

Python looks into the variable item, finds the text "tea" in it and reads the value with that key. Watch the quotes: menu["item"] looks for a key that is literally "item", and there isn't one.

Instructions

The coffee shop doesn't sell juice, so the program ends with KeyError: 'juice'. Fix it with if and in: when the order is on the menu, print its price as before; when it isn't, print Sorry, we don't have juice. (with the name of the order in it). The output should be three lines: tea costs 35, Sorry, we don't have juice. and cake costs 60.

Below the loop, add up the prices of all the orders in a second loop and print Total: 95. Read each price with .get() and the default value 0, so that the juice adds nothing.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/9