Blog |

How to Fix KeyError Exceptions in Python

How to Fix KeyError Exceptions in Python
Table of Contents

The Python KeyError is an exception that occurs when trying to access an item in a dictionary where it does not exist. The key used to access the item is not found in the dictionary, which leads to the KeyError.

As an analogy, it's like trying to open a locker within a set of lockers using a code that doesn't match any of them. In such a case, the system will not be able to find a locker with the code entered and will raise an error. In the context of Python, the set of lockers represents a dictionary and the code is the key you're trying to use to access an item. If the key doesn't exist in the dictionary, Python raises a 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.

KeyError Example

Here’s an example of a Python KeyError raised when trying to access a dictionary item that does not exist:

employees = {"one": "John", "two": "Darren", "three": "Paul"}
print(employees["four"]) #Attempt to access an item that does not exist in dictionary

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 four. Since four does not exist in the set of keys of the dictionary, a KeyError is raised:

File "test.py", line 2, in <module>
    print(employees["four"])
KeyError: 'four'

How to Fix KeyError

Solution One: Check If Key Exists in Dictionary

One approach to avoid the KeyError in Python is to check if the key exists in the dictionary before using it to retrieve items. This can be done using the in keyword.

Using this approach, a check for the key can be added to the earlier example:

employees = {"one": "John", "two": "Darren", "three": "Paul"}

if "four" in employees: #Ensure key exists in dictionary
    print(employees["four"])
else:
    print('Key not found')

Here, a check is performed to ensure that the key four 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

Solution Two: Use .get() to Retrieve Item

Another solution is to use the .get() function to either retrieve the item using the specified key, or a default value of None if it doesn’t exist.

Using this approach, the .get() function can be used to retrieve the item from the dictionary in the earlier example:

employees = {"one": "John", "two": "Darren", "three": "Paul"}

print(employees.get("four")) #Using .get() to retrieve item

Here, the .get() function is used to retrieve an item from employees using the key four. Since they key does not exist in the dictionary, a default value of None is returned and printed, thereby avoiding the KeyError:

None

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!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape