Error Encyclopedia

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

1

Accessing a key that was never added to the dictionary

2

Typo in the key name (case-sensitive, Python dict keys are case-sensitive)

3

Assuming a key exists after filtering or transforming data

4

JSON/API response missing an expected field

5

Using a variable as a key that does not match any existing key

6

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 = 0

Before & After Examples

❌ Before
response = {"status": "ok", "user": {"name": "Bob"}}
email = response["user"]["email"]  # ❌ KeyError: email
✅ After
response = {"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:

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.