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:
>>> 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'
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Dictionaries in Python (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Using Dictionaries in Python (Course)
- Python Dictionaries (Quiz)
- Dictionaries in Python (Quiz)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)