KeyError: key not found in dictionary (Fix)

A KeyError happens when you try to read a dictionary key that is not there.

This usually happens when you use square brackets, like data["age"], but the dictionary does not contain "age". Python raises an error because dictionary keys must match exactly.

This guide shows what the error means, why it happens, and simple ways to fix it.

Quick fix

data = {"name": "Sam"}

# 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 happens when you ask for a dictionary key that does not exist.

It usually appears when using square brackets like data["age"].

Python stops because it cannot find that exact key.

If you are new to dictionaries, see Python dictionaries explained.

Example that causes the error

Here is a small example:

data = {"name": "Sam", "city": "Boston"}

print(data["age"])

Output:

Traceback (most recent call last):
  File "example.py", line 3, in <module>
    print(data["age"])
KeyError: 'age'

The dictionary has "name" and "city", but it does not have "age".

Because of that, data["age"] raises a KeyError.

Why it happens

This error usually happens for one of these reasons:

  • The key is missing from the dictionary.
  • The key name is spelled differently.
  • The key uses different capitalization, such as "Name" vs "name".
  • You expected data from a file or API, but that key was not included.

Common causes include:

  • Accessing a missing key with square brackets
  • Typing the wrong key name
  • Using the wrong letter case in the key
  • Assuming API or JSON data always contains a key
  • Reading user input that does not match dictionary keys

Fix 1: Check if the key exists first

Use if key in my_dict before reading the value.

This is clear and beginner-friendly. It is a good choice when you want different behavior if the key is missing.

data = {"name": "Sam"}

if "age" in data:
    print(data["age"])
else:
    print("Key not found")

Output:

Key not found

This approach makes your program explicit. You decide what should happen when the key is missing.

For a full example, see how to check if a key exists in a dictionary in Python.

Fix 2: Use get() for safe access

dict.get(key) returns None if the key is missing.

You can also give a default value, like dict.get(key, 0).

This is useful when a missing key is normal and should not stop the program.

data = {"name": "Sam"}

print(data.get("age"))
print(data.get("age", 0))

Output:

None
0

This is often the easiest fix for beginners.

If you want to learn this method in more detail, see the Python dictionary get() method.

Fix 3: Inspect the dictionary keys

Sometimes the problem is not that the key is missing. The real problem is that the key name is different from what you expected.

Print the dictionary or its keys to see what is actually available.

data = {"Name": "Sam", "city": "Boston"}

print(data)
print(data.keys())

Output:

{'Name': 'Sam', 'city': 'Boston'}
dict_keys(['Name', 'city'])

Now you can see that the key is "Name", not "name".

You can also use these debugging checks:

my_dict = {"Name": "Sam", "city": "Boston"}
key_name = "name"

print(my_dict)
print(my_dict.keys())
print("wanted key:", key_name)
print("exists:", key_name in my_dict)

Output:

{'Name': 'Sam', 'city': 'Boston'}
dict_keys(['Name', 'city'])
wanted key: name
exists: False

This helps you find:

  • spelling mistakes
  • extra spaces
  • uppercase/lowercase differences

You can learn more about this on the Python dictionary keys() method.

Fix 4: Handle the error with try-except

Use try-except KeyError when missing keys are possible.

This is useful when reading uncertain external data, such as JSON, API responses, or user-provided values.

data = {"name": "Sam"}

try:
    print(data["age"])
except KeyError:
    print("The key was not found")

Output:

The key was not found

What except does:

  • Python tries the code inside try
  • If a KeyError happens, Python runs the except block instead
  • This prevents the program from crashing immediately

Keep this method simple. In many cases, get() or an in check is easier to read.

Common debugging steps

If you are not sure why the error is happening, try these steps:

  • Print the missing key value you are trying to use.
  • Print the dictionary keys before access.
  • Check spelling, spaces, and uppercase/lowercase letters.
  • Confirm the dictionary was filled correctly before reading from it.

Useful debugging commands:

print(my_dict)
print(my_dict.keys())
print("wanted key:", key_name)
print("exists:", key_name in my_dict)

These checks often reveal the problem quickly.

When to use vs get()

Use square brackets [] when the key must exist.

Use get() when the key may be missing.

The difference is important:

  • my_dict["key"] raises KeyError if the key is missing
  • my_dict.get("key") returns None instead
  • my_dict.get("key", default_value) returns your default value

Example:

data = {"name": "Sam"}

# Use this when the key must exist
print(data["name"])

# Use this when the key may be missing
print(data.get("age"))

# Use this when you want a fallback value
print(data.get("age", "Unknown"))

Output:

Sam
None
Unknown

If you want more practice, see how to access values in a dictionary in Python.

FAQ

Why does get() not raise KeyError?

Because get() is designed for safe dictionary access. It returns None or a default value instead of stopping with an error.

Is KeyError the same as IndexError?

No. KeyError is for missing dictionary keys. IndexError is for invalid list or tuple positions.

For a direct comparison, see KeyError vs IndexError in Python explained.

How do I give a default value if a key is missing?

Use dict.get("key", default_value).

Example:

data = {"name": "Sam"}
print(data.get("age", 0))

Can capitalization cause a KeyError?

Yes. Dictionary keys must match exactly, so "Name" and "name" are different keys.

See also

Next step: practice safe dictionary access by using get(), checking keys with in, and learning a few basic dictionary methods.