Skip to content

KeyError

KeyError is a built-in exception that occurs when you try to access a missing key in a dictionary. This usually happens if you try to retrieve or delete a value using a key that doesn’t exist.

You’ll run into this exception when you’re working with dictionaries. To avoid it, you can use methods like .get() with a default value, or check whether the key exists in the dictionary before you access it.

KeyError Occurs When

  • Accessing a dictionary with a key that might not be present
  • Deleting a dictionary entry with a non-existent key
  • Fetching values from nested dictionaries where the structure might vary

KeyError Example

An example of when the exception appears:

Language: Python
>>> fruits = {"apple": 4, "orange": 5, "banana": 2}
>>> fruits["grape"]
Traceback (most recent call last):
    ...
KeyError: 'grape'

KeyError How to Fix It

To fix a KeyError, make sure the key exists in the dictionary before you try to access it. Here’s an example of a buggy piece of code and how to fix it:

Language: Python
>>> prices = {"bread": 1.5, "milk": 1.0, "eggs": 2.0}

>>> # Risky code
>>> prices["butter"]
Traceback (most recent call last):
    ...
KeyError: 'butter'

>>> # Safe code
>>> prices.get("butter", "Price not available")
'Price not available'
Python KeyError Exceptions and How to Handle Them

Tutorial

Python KeyError Exceptions and How to Handle Them

Understand why Python raises a KeyError for bad key lookups in a dictionary. Fix your KeyError now and learn to handle them for smooth scripting.

basics python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Oct. 1, 2026 • Reviewed by Martin Breuss