What does KeyError mean in Python?
Why the error happens
Python raises KeyError when code uses square brackets to read a key that is not in a dictionary, such as data['email'] when the dictionary has no email entry. The message usually shows the missing key name in quotes, which is the first clue to where the problem is.
Common causes include a typo in the key, a key that only exists in some records, or data that came from an API or file in a different shape than you expected. Printing the dictionary's keys just before the failing line often reveals the mismatch quickly.
- Print list(data.keys()) before the failing line
- Check for typos and letter case differences
- Confirm the source data really contains that field
How to fix it
Use data.get('email') when a missing key is acceptable, since it returns None instead of raising an error. You can also supply a default, such as data.get('email', ''). Use an if 'email' in data check when the missing key needs a different path.
If the key should always exist, let the error stay visible so you find the source problem. Hiding it with a default can cause quiet bugs further downstream.
Dictionaries in JSON data often include nested objects, so the key may exist one level deeper than you expect. Printing the full structure with a quick look is faster than guessing.
Common mistakes
- Wrapping the whole block in try except and ignoring the error.
- Using get everywhere without checking why a required key is missing.

Related questions
- What does NullPointerException mean in Java?
- How do I fix IndexError: list index out of range in Python?
- What does TypeError: 'NoneType' object is not subscriptable mean?
- Why do I get a segmentation fault in C?
- What does ValueError: could not convert string to float mean?
- How do I fix a stack overflow error?