What this error means
You tried to access a key in a nested dictionary (a dictionary inside another dictionary), but that key doesn't exist at some level. The error can happen at any level of nesting.
Common causes
- A key is missing at an intermediate level (e.g.,
data['user']['name']but'user'doesn't exist). - The final key doesn't exist (e.g.,
data['user']['email']but'email'is missing). - One of the nested values is
Noneinstead of a dictionary.
Example that causes the error
data = {
'user': {
'name': 'Alice'
# 'email' is missing
}
}
email = data['user']['email'] # KeyError: 'email' doesn't exist
# Or:
data = {} # Empty dict
name = data['user']['name'] # KeyError: 'user' doesn't exist
How to fix it: use .get() with defaults
Use .get() at each level with safe defaults:
data = {'user': {'name': 'Alice'}}
email = data.get('user', {}).get('email', 'No email')
print(email) # "No email" if key missing
# Or check each level:
if 'user' in data and 'email' in data['user']:
email = data['user']['email']
else:
email = 'No email'
Use try-except
try:
email = data['user']['email']
except KeyError:
email = 'No email'
print("Email key not found")
Create a helper function
def safe_get(data, *keys, default=None):
"""Safely get nested dictionary value."""
for key in keys:
if isinstance(data, dict):
data = data.get(key)
else:
return default
return data if data is not None else default
email = safe_get(data, 'user', 'email', default='No email')