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:

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:

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'

Tutorial

Python's Built-in Exceptions: A Walkthrough With Examples

In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.

intermediate python

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


By Leodanis Pozo Ramos • Updated March 13, 2025 • Reviewed by Martin Breuss