A KeyError is raised when you access a dictionary with a key that is not in the dictionary. Dictionaries only allow access to keys that exist; using a missing key is an error, so Python stops execution and reports the key you used. This guide shows why it happens and several ways to fix or avoid it.
What this error means
When you write d[key], Python looks up key in the dictionary d. If the key is not present, Python raises KeyError: 'key' (with the actual key in the message). This is different from IndexError, which happens when you use an invalid index on a list or string.
Common causes
- Misspelled or wrong key. The key name is wrong (e.g.
'adress'instead of'address'), or you assume a key that was never set. - Data from elsewhere. The dict comes from JSON, an API, or user input and does not always have the same keys. One record might have
'city', another might not. - Variable as key. You use a variable for the key; that variable’s value does not match any key in the dict.
- Nested dicts. An inner dict is missing a key—see KeyError with nested dicts for patterns to handle that.
Example that causes the error
person = {'name': 'Alice', 'age': 30}
print(person['city']) # KeyError: 'city' doesn't exist
Fix 1: use .get() (recommended when key may be missing)
.get(key) returns None if the key is missing; .get(key, default) returns default. No exception is raised.
person = {'name': 'Alice', 'age': 30}
city = person.get('city') # None if missing
print(city) # None
city = person.get('city', 'Unknown')
print(city) # 'Unknown'
Fix 2: check with in before access
person = {'name': 'Alice', 'age': 30}
if 'city' in person:
print(person['city'])
else:
print("City not found")
Fix 3: use try-except
Use this when missing keys are exceptional and you want to handle them in one place.
person = {'name': 'Alice', 'age': 30}
try:
city = person['city']
except KeyError:
city = 'Unknown'
print("City key not found, using default")
When to use which
Use .get() when you are fine with a default and do not need to distinguish “key missing” from “value is None”. Use in when you need to branch on presence. Use try/except KeyError when you want to centralize handling or when missing keys are rare.
Next steps: Errors & Exceptions · KeyError: nested dict · Dictionaries