Error guide · KeyError
KeyError
You asked a dictionary for a key it does not contain.
Example
prices = {"pen": 10, "book": 120}
print(prices["bag"])What Python says
KeyError: 'bag'
As printed by Python 3.12. Other versions may word it slightly differently.
Why it happens
Square brackets need the key to exist. Keys must match exactly, including capital letters and spaces.
How to fix it
prices = {"pen": 10, "book": 120}
print(prices.get("bag", 0))Output: 0
Tips
- Use
.get(key, default)when a key might be missing. - Check with
if key in prices:before using it. - Print
prices.keys()to see which keys really exist.