Kurs
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.

I am a freelance data analyst, collaborating with companies and organisations worldwide in data science projects. I am also a data science instructor with 2+ experience. I regularly write data-science-related articles in English and Spanish, some of which have been published on established websites such as DataCamp, Towards Data Science and Analytics Vidhya As a data scientist with a background in political science and law, my goal is to work at the interplay of public policy, law and technology, leveraging the power of ideas to advance innovative solutions and narratives that can help us address urgent challenges, namely the climate crisis. I consider myself a self-taught person, a constant learner, and a firm supporter of multidisciplinary. It is never too late to learn new things.