Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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.

  2. 2

    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.

Back

4/9

  1. 1. What Is a Dictionary?
  2. 2. Reading Values
  3. 3. Changing and Adding Values
  4. 4. Missing Keys
  5. 5. Looping Over a Dictionary
  6. 6. Counting with a Dictionary
  7. 7. Lists of Dictionaries
  8. 8. Functions and Dictionaries
  9. 9. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.