KeyError in Python — What It Means and How to Fix It
What Python's KeyError exception means and how to resolve it.
Published October 27, 2026
KeyError is raised when you look up a key that is not in a dictionary.
What it means and why it happens
Typical causes: typos, missing optional fields in JSON or form data, or assuming keys exist.
Read the full message: it names the file and line where the problem was detected, which is the best place to start.
What you see
run the code
KeyError: 'email'
Practical examples
Code that triggers it
user = {'name': 'Ada'}
print(user['email'])The fix
user = {'name': 'Ada'}
print(user.get('email', 'n/a'))
if 'email' in user: print(user['email'])defaultdict
from collections import defaultdict
counts = defaultdict(int)
counts['a'] += 1Common mistakes
- Using [] on optional keys.
- Mutating a dict while iterating.
- Case mismatches in keys.
Key takeaways
- KeyError: KeyError is raised when you look up a key that is not in a dictionary.
- Read the message and the line number first.
- Fix the cause, don't just silence the error.
FAQ
get() vs []?
get() returns a default instead of raising.
How do I find which line caused KeyError?
The error message and stack trace show the file and line; start there and work backwards.