Skip to main content
HomeTutorialsPython

Python KeyError Exceptions and How to Fix Them

Learn key techniques such as exception handling and error prevention to handle the KeyError exception in Python effectively.
May 2024  · 6 min read

Even the most experienced programmers make coding mistakes. For Python programmers, these mistakes fall into one of two categories: errors or exceptions.

Errors are primarily related to syntax. They must be fixed in order for the program to run. An exception, on the other hand, happens when the code is syntactically correct, but something interrupts the program when it is running. 

In this tutorial, we will look at one of the most common exceptions encountered by both new and experienced programmers: the KeyError exception. We will cover the details of Python’s KeyError, providing examples and different techniques to handle this type of exception. If you want to learn how to identify and fix mistakes in Python, also check out our Exception & Error Handling in Python tutorial. 

What is a KeyError Exception?

In Python, a KeyError exception is one of the built-in exceptions that is designed to handle a wide range of common error conditions. A KeyError exception can be understood as a subclass, along with IndexError, of the more general LookupError exception, all of which are objects of the Exception class.

Specifically, a KeyError exception is raised when a programmer tries to access a key that does not exist in a dictionary. A dictionary, for reference, is a data structure that stores data in key-value pairs, and the value in a dictionary is accessed through its key - hence the name, KeyError

Python KeyError Common Causes and Examples

Let’s look at an example using a dictionary of countries and their capitals:

dictionary_capitals = {'Madrid': 'Spain',
 'Lisboa': 'Portugal', 'London': 'United Kingdom'}

To search for information in our dictionary, we need to specify the key in brackets and Python will return the associated value.

dictionary_capitals['Madrid']
'Spain'

If we try to access a key that is not in the dictionary, Python will give us our KeyError exception error message. 

dictionary_capitals['Rome']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Rome'

We could also encounter the KeyError exception when we try to access non-existent keys in other Python mapping objects that adopt the form of a dictionary. For example, the os.environ object returns a dictionary that stores the user’s environmental variables as keys along with their associated values.

In the following code, we attempt to access the value associated with the key USERS in the os.environ dictionary. Because USERS was not in the os.environ dictionary, our code gives us a KeyError.

#Calling a non-existent environmental variable
os.environ['USERS']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'USERS'

As it turns out, dictionaries are very common in Python. Another such example is the implementation of something more abstract called a hashmap. Check out our Guide to Python Hashmaps tutorial to learn more about hashmaps.

Handling Python KeyError Exceptions

Let's explore methods to handle KeyError exceptions. We have two strategies: We could either prevent KeyError or catch KeyError with error handling. 

Preventing KeyError

As we have seen, Python will throw a KeyError if we try to access a non-existent key. To prevent this, we can access keys in a dictionary using the .get() method in order to make our code more forgiving. If, when using this method, we encounter a nonexistent key, Python will return a None value instead of a KeyError. This is one good approach.

print(dictionary_capitals.get('Prague'))
None

Alternatively, we could check whether a key exists before accessing it. This way of preventing exceptions is known as “Look Before You Leap," or LBYL, for short. In this case, we could use if statements to check if the key exists and, if it doesn’t, we can handle the issue in the else clause.

capital = "Prague"
if capital in dictionary_capitals.keys():
    value = dictionary_capitals[capital]
else:
    print("The key {} is not present in the dictionary".format(capital)) 

Catching KeyError with exception handling

A second approach is known as “Easier to Ask Forgiveness Than Permission." EAFP, as its called, is actually the more standard way to handle exceptions in Python. 

Adopting the EAFP coding style means that we assume the existence of valid keys and catch exceptions if the assumption proves false. While our LBYL approach relies on if/else statements, the EAFP approach relies on try/except clauses. 

In the following example, instead of checking if the key is present, we try to access the desired key. If, for some reason, the key isn’t present, then we just catch the KeyError in the except clause and handle it appropriately.

capital = "Prague"
try:
     value = dictionary_capitals[capital]
except KeyError:
     print("The key {} is not present in the dictionary".format(capital)) 

Advanced Python KeyError Management

Using defaultdict for automatic key handling

We see that, whenever we try to access a key that is not present in our dictionary, Python will return a KeyError exception. The .get() method we reviewed was an error-tolerant approach that worked okay, but it wasn’t optimized.

The Collections module offers defaultdict, which is a more optimized approach for handling dictionary entries. Unlike standard dictionaries that throw a KeyError if we try to access a non-existent key, a defaultdict allows us to specify a default value that is returned whenever a key is not found. The following code shows us how to import defaultdict from Collections and create a default value with a lambda function. If you are confused about lambda functions, check out our Python lambda Tutorial to learn more.

from collections import defaultdict 

# Defining the dict 
capitals = defaultdict(lambda: "The key doesn't exist") 
capitals['Madrid'] = 'Spain'
capitals['Lisboa'] = 'Portugal'
print(capitals['Madrid']) 
print(capitals['Lisboa']) 
print(capitals['Ankara'])
Spain
Portugal
The key doesn't exist

Raising KeyErrors deliberately

Lastly, we should say that, in some circumstances, it might be appropriate to deliberately raise a KeyError to enforce certain constraints.

We know that, in many cases, functions rely on specific data being available to perform their operations. Manually triggering a KeyError therefore ensures that the function fails clearly and predictably when required data is missing. In these cases, the error message provided with the KeyError helps us understand exactly what was wrong with the input provided, which makes debugging easier.

Let’s clarify with an example. Here we have created a function that takes a dictionary as an argument. The user has to provide the dictionary with the right keys for the function to work correctly. We create a function in this case because we want to know right away if the keys are missing, instead of letting errors persist further in the code. 

def my_function(my_dict): 
    if 'critical_key' not in my_dict: 
        raise KeyError('critical_key is missing from the dictionary. Please modify the dictionary')

Conclusion

We hope you enjoyed this article. KeyError is one of the most common exceptions that a Python developer will encounter. Mastering the art of error and exception handling is a key part of becoming a strong Python programmer. Learn more about other functional programming techniques and other coding fundamentals with our Python Programming and Python Fundamentals skill tracks. Also, check out our Python Sets and Set Theory tutorial to learn more about adjacent concepts. 


Photo of Javier Canales Luna
Author
Javier Canales Luna
Topics

Learn Python with DataCamp

Course

Writing Efficient Python Code

4 hr
117.4K
Learn to write efficient code that executes quickly and allocates resources skillfully to avoid unnecessary overhead.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

blog

The 4 Best Data Analytics Bootcamps in 2024

Discover the best data analytics bootcamps in 2024, discussing what they are, how to choose the best bootcamp, and you can learn.

Kevin Babitz

5 min

tutorial

Encapsulation in Python Object-Oriented Programming: A Comprehensive Guide

Learn the fundamentals of implementing encapsulation in Python object-oriented programming.
Bex Tuychiev's photo

Bex Tuychiev

11 min

tutorial

Everything You Need to Know About Python Environment Variables

Learn the ins and outs of managing Python environment variables with os and python-dotenv libraries.
Bex Tuychiev's photo

Bex Tuychiev

9 min

tutorial

Everything You Need to Know About Python's Maximum Integer Value

Explore Python's maximum integer value, including system limits and the sys.maxsize attribute.
Amberle McKee's photo

Amberle McKee

5 min

tutorial

Troubleshooting The No module named 'sklearn' Error Message in Python

Learn how to quickly fix the ModuleNotFoundError: No module named 'sklearn' exception with our detailed, easy-to-follow online guide.
Amberle McKee's photo

Amberle McKee

5 min

code-along

Getting Started With Data Analysis in Alteryx Cloud

In this session, you'll learn how to get started with the Alteryx AI Platform by performing data analysis using Alteryx Designer Cloud.
Joshua Burkhow's photo

Joshua Burkhow

See MoreSee More