Skip to content

Fixing Python KeyError: Troubleshooting and Solutions

Python KeyError Exceptions and How to Handle Them

Table of Contents

Python’s KeyError exception is a common exception encountered by beginners. Knowing why a KeyError can be raised and some solutions to prevent it from stopping your program are essential steps to improving as a Python programmer.

By the end of this tutorial, you’ll know:

  • What a Python KeyError usually means
  • Where else you might see a KeyError in the standard library
  • How to handle a KeyError when you see it

What a Python KeyError Usually Means

A Python KeyError exception is raised when you try to access a key that isn’t in a dictionary (dict). It is raised when a mapping key is accessed and isn’t found in the mapping. The most common mapping in Python is the dictionary.

In the following example, a dictionary ages is defined with the ages of three people. When you try to access a key that is not in the dictionary, a KeyError is raised:

ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
ages['Michael'] # Raises KeyError

Here, attempting to access the key 'Michael' in the ages dictionary results in a KeyError being raised.

Where Else You Might See a Python KeyError in the Standard Library

A KeyError can be encountered when working with various data structures and modules in the Python standard library. Here are some examples:

  • With the configparser module, if you try to access a non-existent section or option in a configuration file.
  • With the os.environ dictionary, if you try to access an undefined environment variable.
  • With the sys.argv list, if you try to access a command-line argument that wasn’t provided.
  • With the re module, if you try to access a named capturing group that didn’t match in a regular expression.

These are just a few examples, and there are many other cases where a KeyError can be encountered in the standard library.

When You Need to Raise a Python KeyError in Your Own Code

While encountering a KeyError may not be ideal when running your code, there might be situations where you intentionally want to raise a KeyError in your own code. For example, you might want to ensure that a certain key is present in a dictionary, and if not, raise a KeyError to signal an error condition.

Here’s an example of raising a KeyError in your own code:

def get_value(data, key):
if key not in data:
raise KeyError(f"Key '{key}' doesn't exist in data")
return data[key]

In this example, the get_value() function takes a dictionary data and a key as arguments. It checks if the key exists in the data dictionary, and if not, raises a KeyError with a helpful error message.

How to Handle a Python KeyError When You See It

When encountering a KeyError in your code, you have a few options to handle it gracefully and prevent your program from stopping abruptly.

The Usual Solution: .get()

One common solution is to use the .get() method of dictionaries instead of direct key access. The .get() method returns the value associated with the given key, or a default value if the key doesn’t exist.

ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
# Accessing key with .get() method
age = ages.get('Michael', 'Unknown')
print(age) # Prints 'Unknown'

In this example, the .get() method is used to retrieve the age associated with the key 'Michael'. Since the key doesn’t exist in the dictionary, the method returns the default value 'Unknown'.

The Rare Solution: Checking for Keys

Another solution is to check if a key exists in a dictionary before accessing it using the in operator. This way, you can handle the case where the key doesn’t exist without raising a KeyError.

ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
# Checking if key exists before accessing
if 'Michael' in ages:
age = ages['Michael']
age = 'Unknown'
print(age) # Prints 'Unknown'

In this example, the 'Michael' key is checked using the in operator before accessing it. If the key exists, its value is assigned to the age variable. Otherwise, the variable is assigned the value 'Unknown'.

The General Solution: try except

The most general solution is to use a try except block to catch the KeyError and handle it appropriately. This allows you to perform specific actions or display custom error messages when a KeyError occurs.

ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
# Handling KeyError with try except
person = input('Get age for: ')
age = ages[person]
except KeyError:
age = 'Unknown'
print(f'{person} is {age} years old.')

In this example, the person variable is used as the key to retrieve the age from the ages dictionary. If a KeyError is raised because the key doesn’t exist, the code inside the except block is executed, which assigns the 'Unknown' value to the age variable.


Understanding how to handle a KeyError is an important skill for Python programmers. By knowing what a KeyError usually means, where else you might encounter it, and how to handle it using .get(), checking for keys, or try except, you can prevent your programs from crashing and handle error conditions in a more controlled manner.