KeyError when accessing dictionary values (Fix)
A KeyError happens when you try to access a dictionary value using a key that does not exist.
This usually happens with square bracket access like data["age"]. If the key is missing, Python stops and raises an error.
This page shows what the error means, why it happens, and how to fix it safely.
Quick fix
data = {"name": "Ana"}
# Safe access
value = data.get("age")
print(value) # None
# Or check first
if "age" in data:
print(data["age"])
else:
print("Key not found")
Use dict.get() when a key might be missing, or check with in before using square brackets.
What this error means
A KeyError means Python could not find the key in the dictionary.
For example:
data = {"name": "Ana"}
print(data["age"])
This raises:
KeyError: 'age'
Why?
- The dictionary only has the key
"name". - You asked for
"age". - Dictionary keys must match exactly.
If you are new to dictionaries, see Python dictionaries explained.
Why it happens
Common reasons include:
- The key does not exist in the dictionary.
- The key name has different spelling or capitalization.
- You expected data from a file, API, or user input, but the key is missing.
- You removed the key earlier with
pop()ordel.
A few examples:
data = {"name": "Ana"}
print(data["Name"]) # different capitalization
print(data[" name"]) # leading space
print(data["age"]) # missing key
All of these can raise KeyError.
Example that causes the error
Here is a simple example:
person = {"name": "Ana"}
print(person["age"])
Output:
KeyError: 'age'
What happens here:
personcontains one key:"name"- The code tries to read
"age" - Python raises
KeyErrorbecause"age"is not present
If you want to learn the normal way to read dictionary values, see how to access values in a dictionary in Python.
Fix 1: Use get() for optional keys
Use .get() when a key might be missing.
person = {"name": "Ana"}
age = person.get("age")
print(age)
Output:
None
You can also provide a default value:
person = {"name": "Ana"}
age = person.get("age", 0)
print(age)
Output:
0
Why this helps:
person["age"]raisesKeyErrorperson.get("age")returnsNoneinsteadperson.get("age", 0)returns0if the key is missing
This is useful when missing data is expected.
If you want more detail, see the Python dictionary get() method.
Fix 2: Check if the key exists first
You can check before reading the value:
person = {"name": "Ana"}
if "age" in person:
print(person["age"])
else:
print("Key not found")
Output:
Key not found
This is a clear and beginner-friendly approach.
Use this when:
- You want different behavior for missing keys
- You want to print a message
- You want to avoid an error before it happens
For a full example, see how to check if a key exists in a dictionary in Python.
Fix 3: Handle the error with try-except
You can catch the error with try-except:
person = {"name": "Ana"}
try:
print(person["age"])
except KeyError:
print("The key was not found")
Output:
The key was not found
This is useful when:
- The key might be missing
- You want to handle the problem without stopping the program
- The missing key is part of normal program flow
Keep the try block small. That makes debugging easier.
You can also use a fallback value:
person = {"name": "Ana"}
try:
age = person["age"]
except KeyError:
age = 0
print(age)
Output:
0
How to debug a KeyError
If you are not sure why the error happens, inspect the dictionary first.
Useful debugging commands:
print(data)
print(data.keys())
print("age" in data)
print(repr(user_key))
print(type(user_key))
What these help you check:
print(data)shows the full dictionaryprint(data.keys())shows the available keysprint("age" in data)checks whether a specific key existsprint(repr(user_key))helps reveal hidden spaces like"age "print(type(user_key))shows whether the key is a string, integer, or something else
Example:
data = {"name": "Ana", "age ": 25}
user_key = "age"
print(data)
print(data.keys())
print(repr(user_key))
print(user_key in data)
Output:
{'name': 'Ana', 'age ': 25}
dict_keys(['name', 'age '])
'age'
False
Here the real key is "age " with a trailing space, not "age".
If your dictionary came from JSON, inspect the full data before assuming a field exists. See how to parse JSON in Python.
Common real examples
These are very common beginner cases:
Reading JSON data and assuming a field always exists
data = {"name": "Ana"}
email = data.get("email")
print(email)
If you used data["email"], this would raise KeyError.
Using user input as a dictionary key without checking it
prices = {"apple": 2, "banana": 3}
item = "orange"
if item in prices:
print(prices[item])
else:
print("Item not found")
Looking up a key after removing it
data = {"name": "Ana", "age": 20}
del data["age"]
print(data.get("age"))
Confusing string keys and integer keys
data = {"1": "one", 2: "two"}
print(data["1"]) # works
print(data[2]) # works
But this would fail:
data = {"1": "one"}
print(data[1])
Output:
KeyError: 1
The string "1" and the integer 1 are different keys.
Related errors
Some related pages may also help:
- A broader explanation of this exception: KeyError in Python: causes and fixes
- A closely related dictionary problem: KeyError: key not found in dictionary (fix)
- If you are working with dictionary methods, you may also need Python dictionary get() method
Common mistakes
These are frequent causes of KeyError:
- Using
data["missing_key"]when the key is not in the dictionary - Wrong capitalization, such as
"Name"instead of"name" - Leading or trailing spaces in the key
- Expecting a key from JSON or API data that is not always included
- Mixing string keys and integer keys
- Removing a key earlier in the program
FAQ
What is the difference between data["key"] and data.get("key")?
Square brackets raise KeyError if the key is missing. get() returns None or a default value.
Should I always use get() instead of square brackets?
No. Use square brackets when the key must exist. Use get() when the key might be missing.
Can KeyError happen with JSON data?
Yes. JSON objects become Python dictionaries, so missing fields can cause KeyError.
Why does my key look correct but still fail?
Check capitalization, spaces, and whether the key is a string or a number.
See also
- Python dictionaries explained
- Python dictionary get() method
- How to access values in a dictionary in Python
- How to check if a key exists in a dictionary in Python
- How to parse JSON in Python
Once you fix this error, the next step is learning how to safely read dictionary data in everyday code. Using .get(), checking with in, and inspecting real input data will help you avoid KeyError in the future.