Python KeyError — Dictionary Key Not Found

Fix Python KeyError exceptions. Learn safe dictionary access patterns, defaultdict usage, environment variable handling, and common data processing pitfalls.

Python Exceptions

Detailed Explanation

Python KeyError

A KeyError is raised when you try to access a dictionary key that does not exist. It is the most common Python exception in data processing and web applications.

Basic Example

data = {"name": "John", "age": 30}
print(data["email"])  # KeyError: 'email'

Safe Access Patterns

1. dict.get() with default:

email = data.get("email", "not provided")
# Returns "not provided" instead of raising KeyError

2. Check before access:

if "email" in data:
    email = data["email"]

3. try/except:

try:
    email = data["email"]
except KeyError:
    email = None

4. collections.defaultdict:

from collections import defaultdict

# Automatically creates missing keys with a default factory
word_counts = defaultdict(int)
for word in words:
    word_counts[word] += 1  # No KeyError for new words

Common Scenarios

Environment variables:

import os

# Bad: raises KeyError if not set
secret = os.environ["SECRET_KEY"]

# Good: provide a default or fail explicitly
secret = os.environ.get("SECRET_KEY", "dev-secret")

# Good: fail with a clear message
secret = os.environ.get("SECRET_KEY")
if secret is None:
    raise ValueError("SECRET_KEY environment variable is required")

JSON API responses:

response = requests.get("https://api.example.com/user")
data = response.json()

# Bad: assumes "email" always exists
email = data["user"]["email"]

# Good: safe nested access
email = data.get("user", {}).get("email")

Pandas DataFrames:

# KeyError with DataFrame column access
df["nonexistent_column"]  # KeyError

# Check first
if "column" in df.columns:
    values = df["column"]

Python 3.10+ Structural Pattern Matching

match data:
    case {"email": email, "name": name}:
        print(f"{name}: {email}")
    case {"name": name}:
        print(f"{name}: no email")

Use Case

KeyError is the most common exception in Python data processing, API integrations, and configuration management. Whether you are parsing JSON API responses, reading environment variables, or processing CSV data, understanding safe dictionary access patterns prevents runtime crashes and makes code more robust in production.

Try It — Error Code Reference

Open full tool