Skip to main content

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.


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

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
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/", 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.


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]
    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"
     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'
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')


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
Javier Canales Luna

Learn Python with DataCamp


Writing Efficient Python Code

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


Exception & Error Handling in Python

Errors and exceptions can lead to program failure or unexpected behavior, and Python comes with a robust set of tools to improve the stability of the code.
Abid Ali Awan's photo

Abid Ali Awan

21 min


Top Techniques to Handle Missing Values Every Data Scientist Should Know

Explore various techniques to efficiently handle missing values and their implementations in Python.
Zoumana Keita 's photo

Zoumana Keita

15 min


Python Dictionaries Tutorial

Learn how to create a dictionary in Python.
DataCamp Team's photo

DataCamp Team

3 min


Python Decorators Tutorial

In this tutorial, learn how to implement decorators in Python.
Derrick Mwiti's photo

Derrick Mwiti

7 min


Python Functions Tutorial

A tutorial on functions in Python that covers how to write functions, how to call them, and more!
Karlijn Willems's photo

Karlijn Willems

14 min


21 Essential Python Tools

Learn about the essential Python tools for software development, web scraping and development, data analysis and visualization, and machine learning.
Abid Ali Awan's photo

Abid Ali Awan

6 min

See MoreSee More