Dictionary key not found
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.
- 1A typo in the key's name.
- 2Incorrectly assuming a key will always be present in the data.
- 3Using a different data type for the key during access than was used for storage (e.g., `1` vs `'1'`).
This error is triggered when trying to access a dictionary key ('age') that was never added to it.
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.
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.
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.
d = {"name": "Alice"}
val = d["age"] # KeyError: 'age'try:
val = d["age"]
except KeyError as e:
print(f"Key not found: {e}")
val = Noneval = d.get("age", "unknown") # returns default, never raises KeyError✕ 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`.
cpython/Objects/dictobject.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev