KeyError in Python: Causes and Fixes
A KeyError in Python usually happens when you try to read a dictionary value using a key that does not exist.
This error is very common when working with dictionaries, JSON data, and API responses. The good news is that it is usually easy to fix once you know why it happens.
Quick fix
data = {"name": "Ana"}
# Safe access
print(data.get("age")) # None
print(data.get("age", 0)) # 0
# Check before access
if "age" in data:
print(data["age"])
else:
print("Key not found")
Use dict.get() when a key may be missing, or check with in before using square brackets.
What KeyError means
A KeyError happens when you try to access a dictionary key that does not exist.
It is most common with square bracket access like data["missing_key"].
Python raises the error because it cannot find that key in the dictionary.
A simple example that causes KeyError
Here is a small example:
user = {
"name": "Ana",
"country": "Spain"
}
print(user["name"])
print(user["age"]) # This line raises KeyError
Output:
Ana
Traceback (most recent call last):
...
KeyError: 'age'
The dictionary has "name" and "country", but it does not have "age".
So user["age"] causes the error.
If you need a refresher on dictionaries, see Python dictionaries explained.
Why this error happens
KeyError usually happens for one of these reasons:
- The key was never added to the dictionary.
- The key name is misspelled.
- The key uses different uppercase or lowercase letters.
- You expected input data to contain a key, but it does not.
- You removed the key earlier with
pop()ordel.
Here is a case-sensitive example:
data = {"name": "Ana"}
print(data["Name"]) # KeyError
"name" and "Name" are different keys in Python.
How to fix KeyError
There are several common fixes:
- Use
dict.get()if the key may be missing. - Check with
if key in dictionarybefore accessing it. - Add the missing key before reading it.
- Use
try-except KeyErrorwhen missing keys are expected and you want custom handling.
Choose the fix based on what your program should do when the key is not present.
Use get() for safe dictionary access
get() is often the easiest fix for beginners.
get()returnsNoneby default if the key is missing.- You can give
get()a fallback value like0or"unknown". - It avoids the error completely.
Example:
student = {"name": "Leo"}
print(student.get("name"))
print(student.get("grade"))
print(student.get("grade", "Not assigned"))
Output:
Leo
None
Not assigned
This is useful when a missing key is normal and should not stop the program.
You can learn more on the Python dictionary get() method.
Check if a key exists first
Use in when you want different logic for found and missing keys.
profile = {"username": "mila"}
if "email" in profile:
print(profile["email"])
else:
print("Email address is missing")
Output:
Email address is missing
This avoids the error before it happens.
For more examples, see how to check if a key exists in a dictionary in Python.
Handle KeyError with try and except
Use try-except when missing keys are possible and you want to recover cleanly.
This is helpful for:
- User input
- Files
- JSON data
- API responses
Example:
response = {"status": "ok"}
try:
print(response["message"])
except KeyError:
print("The 'message' field is missing")
Output:
The 'message' field is missing
Keep the except block simple and specific.
If you want to understand this pattern better, read how to handle exceptions in Python.
Common debugging steps
When you get a KeyError, check the actual data before changing your code.
Useful debugging commands:
print(my_dict)
print(my_dict.keys())
print("name" in my_dict)
print(type(my_dict))
These checks help you answer questions like:
- What keys are really present?
- Is the key spelled correctly?
- Is the capitalization correct?
- Is the value actually a dictionary?
You can also inspect keys directly with the Python dictionary keys() method.
KeyError with JSON and API data
JSON objects often become Python dictionaries after loading them.
A field may be present in one response but missing in another. That means code like this can fail:
data = {
"user": "Ana"
}
print(data["email"]) # KeyError
A safer version uses get():
data = {
"user": "Ana"
}
email = data.get("email", "No email provided")
print(email)
Output:
No email provided
This is a common pattern when working with external data, because you cannot always assume every field exists.
Related dictionary methods to know
These methods are useful when working with dictionary keys:
get()for safe lookupkeys()to inspect available keysitems()to loop through key-value pairspop()to remove a key safely when used with a default value
Example:
data = {"name": "Ana", "age": 25}
print(data.keys())
print(data.items())
print(data.pop("city", "Key not found"))
Output:
dict_keys(['name', 'age'])
dict_items([('name', 25), ('age', 25)])
Key not found
Common mistakes
These are some of the most common causes of KeyError:
- Accessing a missing dictionary key with square brackets
- Misspelling the key name
- Using the wrong letter case, such as
"Name"instead of"name" - Expecting JSON or API data to always contain the same fields
- Removing a key earlier in the program
- Confusing dictionary keys with list indexes
Example of a misspelled key:
person = {"first_name": "Liam"}
print(person["frist_name"]) # KeyError because the key is misspelled
FAQ
What is the difference between dictkey and dict.get(key)?
dict[key] raises KeyError if the key is missing.dict.get(key) returns None or a default value instead.
Does KeyError only happen with dictionaries?
It mostly happens with dictionaries, but it can also appear in other mapping-like objects that use keys.
How do I avoid KeyError in beginner code?
Use get() for optional keys, or check with in before reading a value.
Why do I get KeyError when reading JSON?
Some JSON data does not include every field every time. A missing field becomes a missing dictionary key in Python.
See also
- Python dictionary get() method
- Python dictionary keys() method
- Python dictionaries explained
- How to check if a key exists in a dictionary in Python
- How to access values in a dictionary in Python
- How to handle exceptions in Python
- KeyError: key not found in dictionary fix
- KeyError when accessing dictionary values fix