All Python errors
KeyError in Python: no such key in the dictionary
KeyError means the dictionary has no key you asked for; the message shows that key. To fix it, check the spelling of the key, test it with in, or read it with get() and a default value.
Code with the error
pet = {"kind": "cat", "years": 4}
print(pet["color"])
Error message (Python 3.12, last line)
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: DictionariesFrequently 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.