KeyError
PythonERRORNotableRuntime ErrorHIGH confidence

Dictionary key not found

What this means

Raised when a dictionary key is accessed but is not found in the set of existing keys. This is specific to dictionaries and other mapping types.

Why it happens
  1. 1A typo in the key's name.
  2. 2Incorrectly assuming a key will always be present in the data.
  3. 3Using a different data type for the key during access than was used for storage (e.g., `1` vs `'1'`).
How to reproduce

This error is triggered when trying to access a dictionary key ('age') that was never added to it.

trigger — this will error
trigger — this will error
my_dict = {"name": "Alice"}
print(my_dict["age"])

expected output

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 'age'

Fix 1

Use the `.get()` method with a default value

WHEN When it's acceptable for a key to be missing and you have a fallback value.

Use the `.get()` method with a default value
my_dict = {"name": "Alice"}
# .get() returns None if 'age' is not found, instead of raising an error
age = my_dict.get("age", "N/A") 
print(age)

Why this works

The `.get()` dictionary method is designed for safe key access. It returns the value for the key if it exists, otherwise it returns the default value you provide (or `None`).

Fix 2

Check for key existence with the `in` keyword

WHEN When you need to perform different actions depending on whether a key exists.

Check for key existence with the `in` keyword
my_dict = {"name": "Alice"}
if "age" in my_dict:
    print(my_dict["age"])
else:
    print("Age is not available.")

Why this works

The `in` keyword provides a clear and efficient way to check for the presence of a key before attempting to access it, avoiding the error.

Code examples
Triggerpython
d = {"name": "Alice"}
val = d["age"]  # KeyError: 'age'
Handle with try/exceptpython
try:
    val = d["age"]
except KeyError as e:
    print(f"Key not found: {e}")
    val = None
Avoid with .get()python
val = d.get("age", "unknown")  # returns default, never raises KeyError
What not to do

Putting every dictionary access in a `try...except KeyError` block

While sometimes necessary, using `.get()` or an `in` check is often more readable and expresses the intent more clearly than a generic `try/except`.

Sources
Official documentation ↗

cpython/Objects/dictobject.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors