The Python KeyError
is an exception that occurs when an attempt is made to access an item in a dictionary that does not exist. The key used to access the item is not found in the dictionary, which leads to the KeyError
.
What Causes KeyError
The Python KeyError
is raised when a mapping key is not found in the set of existing keys of the mapping. In Python, the most common mapping is the dictionary. When an item in a dictionary is accessed using a key, and the key is not found within the set of keys of the dictionary, the KeyError
is raised.
Python KeyError Example
Here’s an example of a Python KeyError
raised when trying to access a dictionary item that does not exist:
employees = {1: "John", 2: "Darren", 3: "Paul"}
print(employees[4])
In the above example, the dictionary employees
contains some key-value pairs. An attempt is then made to access an item from employees
using the key 4
. Since 4
does not exist in the set of keys of the dictionary, a KeyError
is raised:
File "test.py", line 2, in <module>
print(employees[4])
KeyError: 4
How to Fix KeyError in Python
To avoid the KeyError
in Python, keys in a dictionary should be checked before using them to retrieve items. This will help ensure that the key exists in the dictionary and is only used if it does, thereby avoiding the KeyError
. This can be done using the in
keyword.
Another solution is to use the .get()
function to either retrieve the item using the specified key, or None
if it doesn’t exist.
Using the above approach, a check for the key can be added to the earlier example:
employees = {1: "John", 2: "Darren", 3: "Paul"}
if 4 in employees:
print(employees[4])
else:
print('Key not found')
Here, a check is performed to ensure that the key 4
exists in the employees
dictionary before it is used to retrieve a value. If it does not exist, a message is displayed and the error is avoided:
Key not found
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!