KeyError: '...'
KeyError: '...'
DodaTech
2 min read
KeyError: '...' is raised when you try to access a dictionary key that doesn’t exist using the square bracket syntax dict[key]. It’s Python’s way of saying “that key isn’t in this dictionary.”
What It Means
Dictionaries map keys to values. When you use my_dict["some_key"] and "some_key" isn’t in the dictionary, Python raises a KeyError instead of silently returning nothing.
Why It Happens
- The key genuinely doesn’t exist in the dictionary
- The key was misspelled (typo in the key name)
- The data source changed (e.g. an API removed a field)
- The key was added conditionally and the condition wasn’t met
- You’re looking for a key with a different type (e.g. integer vs string:
1vs"1")
How to Fix It
Step 1: Use .get() with a default value
data = {"name": "Alice", "age": 30}
# BAD — raises KeyError if 'city' is missing
print(data["city"])
# GOOD — returns None (or your default) if key is missing
print(data.get("city"))
print(data.get("city", "Unknown"))Step 2: Check with in before accessing
data = {"name": "Alice", "age": 30}
# Safe access
if "city" in data:
print(data["city"])
else:
print("city not found")Step 3: Use setdefault() for default values
data = {"name": "Alice"}
# Set a default only if the key doesn't exist
city = data.setdefault("city", "New York")
print(city) # "New York"
print(data) # {'name': 'Alice', 'city': 'New York'}Step 4: Use a defaultdict for automatic defaults
from collections import defaultdict
# Automatically creates missing keys with a default value
data = defaultdict(list)
data["users"].append("Alice") # No KeyError!
data["users"].append("Bob")
print(dict(data)) # {'users': ['Alice', 'Bob']}Step 5: Wrap in try/except
data = {"name": "Alice"}
try:
value = data["city"]
except KeyError:
value = "Unknown"
print("Key 'city' not found, using default")Step 6: Check key types
data = {1: "integer key"}
# BAD — key is integer, but you used a string
print(data["1"])
# GOOD
print(data[1])Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro