Code with the error

pet = {"kind": "cat", "years": 4}
print(pet["color"])

Error message (Python 3.12, last line)

KeyError: 'color'

Corrected code

pet = {"kind": "cat", "years": 4}
print(pet.get("color", "unknown"))

Output

unknown

Common causes

  • A typo or different letter case in the key.
  • The key is a number but you ask with text, or the other way round: 1 and "1".
  • The key has not been added yet.
  • The key was removed earlier in the program.

Practise in the course

Lesson: Dictionaries

Frequently asked questions

What does get() return for a missing key?

None, or the second argument if you pass one.

How do I check that a key exists?

Use the in operator: if "color" in pet.