error python
Python KeyError
Understanding Python KeyError - raised when a dictionary key is not found in the dictionary.
What It Means
KeyError is raised when you try to access a dictionary key that doesn’t exist. It also occurs when accessing items in other mapping types (like collections.OrderedDict) with a missing key.
The error message shows the key that was not found: KeyError: 'missing_key'.
Common Causes
- Accessing a dictionary with a key that doesn’t exist
- Typo in the key name
- Expected key was never added to the dictionary
- API response missing expected fields
- Environment variable not set (when using
os.environ['KEY']) - JSON data structure different than expected
- Pandas DataFrame column not found
How to Fix
Use .get() with a default value
data = {"name": "John", "age": 30}
# Bad: raises KeyError if key is missing
email = data["email"] # KeyError: 'email'
# Good: returns None if key is missing
email = data.get("email") # None
# Good: returns a default value
email = data.get("email", "not provided") # "not provided"
Check if key exists first
data = {"name": "John", "age": 30}
if "email" in data:
email = data["email"]
else:
email = "default@example.com"
Use try/except
try:
value = data["key"]
except KeyError:
value = "default"
Use collections.defaultdict
from collections import defaultdict
# Automatically creates missing keys with a default value
counts = defaultdict(int)
counts["apples"] += 1 # No KeyError, starts at 0
lists = defaultdict(list)
lists["fruits"].append("apple") # No KeyError, starts as []
Fix environment variable access
import os
# Bad: raises KeyError if not set
api_key = os.environ["API_KEY"]
# Good: returns None or default
api_key = os.environ.get("API_KEY")
api_key = os.environ.get("API_KEY", "default-key")
# Good: raise a clear error
api_key = os.environ.get("API_KEY")
if not api_key:
raise ValueError("API_KEY environment variable is required")
Fix JSON/API response handling
import requests
response = requests.get("https://api.example.com/user")
data = response.json()
# Bad: assumes structure
name = data["user"]["profile"]["name"] # KeyError if any level is missing
# Good: safe nested access
name = data.get("user", {}).get("profile", {}).get("name", "Unknown")
Fix Pandas KeyError
import pandas as pd
df = pd.DataFrame({"name": ["Alice"], "age": [30]})
# Bad: column doesn't exist
# email = df["email"] # KeyError: 'email'
# Good: check first
if "email" in df.columns:
email = df["email"]
# Good: use .get() equivalent
email = df.get("email", pd.Series(["N/A"]))
Related Errors
- Python IndexError - Accessing a list index that’s out of range.
- Python AttributeError - Accessing an attribute that doesn’t exist on an object.
- Python TypeError - Using the wrong type as a dictionary key.