KeyError: 'x'
Error message
'x'
Quick summary
You tried to get a value from a dictionary using a key that isn't in the dictionary.
Why this happens
Typo in the key name
The key was never added to the dictionary
The key was deleted or the data source doesn't include it
Minimal example
d = {"a": 1}
print(d["b"])d = {"a": 1}
print(d.get("b", 0))d["b"] raises KeyError because "b" isn't in the dict — .get("b", 0) returns the default 0 instead.
How to diagnose
Print the dictionary keys with
dict.keys()to see what's availableCheck the key spelling against the actual keys
Verify the key exists with
if key in dictbefore accessing
How to fix
Use
dict.get(key)which returnsNoneinstead of raising KeyErrorUse
dict.get(key, default)to provide a fallback valueCheck
if key in dictbefore accessing withdict[key]
How to prevent
Use
.get()instead of[]when the key might not existUse
defaultdictfromcollectionsfor dictionaries with default values
Related Resources
Related Glossary
Related Lessons
- Data Types
Learn about Python dictionaries and data types
Related Practice
- Python Dynamic Typing
Understand Python's type system for dictionaries.