Python KeyError
The code tries to access a dictionary key that doesn't exist.
Explanation
KeyError occurs when you try to access a dictionary key that doesn't exist in the dictionary. Unlike list indexing which uses numeric positions, dictionary access uses arbitrary keys. If the key hasn't been added to the dictionary, Python raises KeyError. This commonly happens when processing JSON API responses where expected keys are missing, when using defaultdict but the key is accessed incorrectly, or when dictionary key names are misspelled.
Common Causes
- Dictionary key doesn't exist
- Misspelled key name
- API response missing expected keys
- JSON structure different than expected
- Case-sensitive key mismatch
Solution
Use dict.get(key, default) instead of dict[key] to provide a default value. Use defaultdict from collections module to provide default values for missing keys. Check if a key exists with the in operator before accessing it. Use try-except KeyError blocks for handling missing keys. Verify key names match exactly (case-sensitive). Use the setdefault() method to set defaults while accessing.
Code Example
# KeyError from missing key
user = {'name': 'John', 'age': 30}
email = user['email'] # KeyError: 'email'
# Fix: use get with default
email = user.get('email', 'Not provided')
# Check key existence
if 'email' in user:
email = user['email']
# Using defaultdict
from collections import defaultdict
counter = defaultdict(int) # default value is 0
counter['missing'] += 1 # no KeyError, returns 0
# Nested dictionary access
config = {'database': {'host': 'localhost'}}
port = config['database']['port'] # KeyError: 'port'
# Fix: safe nested access
def safe_get(d, *keys, default=None):
for key in keys:
if isinstance(d, dict):
d = d.get(key, default)
else:
return default
return d
port = safe_get(config, 'database', 'port', default=3306)
Error Information
Language
python
Difficulty
Beginner
Views
106
Related Errors
Python
Python SyntaxError
Python detected invalid syntax in the source code.
Python
Python ValueError
A function received an argument of correct type but inappropriate value.
Python
Python PermissionError
The code lacks the necessary permissions to access a file or directory.
Python
Python ModuleNotFoundError
Python cannot find the specified module in the installed packages or system path.