KeyError
Fix Python KeyError when accessing dictionary keys that do not exist. Learn to use .get(), setdefault(), and try-except safely.
What Does This Error Mean?
KeyError occurs when you try to access a dictionary key that does not exist using bracket notation (dict[key]). Python raises this exception because dictionaries have no concept of default values for missing keys — you must explicitly handle the missing key case.
Common Causes
Accessing a key that was never added to the dictionary
Typo in the key name (case-sensitive, Python dict keys are case-sensitive)
Assuming a key exists after filtering or transforming data
JSON/API response missing an expected field
Using a variable as a key that does not match any existing key
Modifying dictionary keys while iterating over them
How to Fix It
Use the .get() method
.get() returns None (or a default value) instead of raising KeyError.
user = {"name": "Alice", "age": 30}
# ❌ Raises KeyError
print(user["email"])
# ✅ Returns None
print(user.get("email"))
# ✅ Returns a default value
print(user.get("email", "no-email@example.com"))Check before access with 'in'
Use the 'in' operator to check if a key exists before accessing it.
user = {"name": "Alice", "age": 30}
if "email" in user:
print(user["email"])
else:
print("Email not found")
# Or use a conditional expression
email = user["email"] if "email" in user else "default@example.com"Use defaultdict for missing keys
Use collections.defaultdict to automatically create default values for missing keys.
from collections import defaultdict
# Regular dict raises KeyError
scores = {}
scores["Alice"].append(95) # ❌ KeyError
# defaultdict creates a default value automatically
scores = defaultdict(list)
scores["Alice"].append(95) # ✅ Works!
scores["Alice"].append(88)
print(scores["Alice"]) # [95, 88]
# Common defaults: list, set, int (0), str (""), dict ({})Use try-except for exception handling
Catch KeyError when the key may or may not exist.
data = {"temp": 72}
try:
humidity = data["humidity"]
print(f"Humidity: {humidity}")
except KeyError:
print("Humidity data not available")
humidity = 0Before & After Examples
response = {"status": "ok", "user": {"name": "Bob"}}
email = response["user"]["email"] # ❌ KeyError: emailresponse = {"status": "ok", "user": {"name": "Bob"}}
email = response.get("user", {}).get("email", "unknown@example.com") # ✅Related Tools
Use these tools to debug and fix this error:
Related Errors
Other common errors in this category:
ModuleNotFoundError: No module named
Fix 'ModuleNotFoundError: No module named' errors in Python. Learn to install missing packages, fix import paths, and manage virtual environments.
IndentationError: unexpected indent
Fix 'IndentationError: unexpected indent' in Python. Learn Python's indentation rules and how to fix spacing issues.
ImportError: cannot import name
Fix 'ImportError: cannot import name' in Python. Learn why imports fail within modules and how to restructure your code to avoid circular dependencies.
AttributeError: 'NoneType' object has no attribute
Fix AttributeError: 'NoneType' object has no attribute errors in Python. Learn why functions return None and how to handle missing return values.
Frequently Asked Questions
What is the difference between dict[key] and dict.get(key)?
dict[key] raises KeyError if the key is missing. dict.get(key) returns None (or a default value you specify) if the key is missing. Always prefer .get() when you are unsure if a key exists.
How does KeyError differ from IndexError?
KeyError applies to dictionaries — accessing a non-existent key. IndexError applies to sequences (lists, tuples, strings) — accessing an index outside the valid range.