KeyError | Python’s Built-in Exceptions – Real Python

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:

>>> 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:

>>> 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'

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