Write Python. Understand every error.

Open the editor

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.

Try this code in Py-CRAFT

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

Learn the ideas behind it

Other common errors

Share this page: