How to Fix KeyError Exceptions in Python

KeyError in Python an exception that occurs when you try to access a key that does not exist in a dictionary.

Written by Satyam Tripathi
Published on Sep. 19, 2023
How to Fix KeyError Exceptions in Python
Image: Shutterstock / Built In
Brand Studio Logo

Python is the most used language by programmers due to its wide range of features and capabilities. During the development of any application in Python, various types of errors can occur, and one of the most common errors is the KeyError exception, which is generally encountered by beginners.

What Is a KeyError in Python?

A KeyError in Python occurs when the user tries to access a key that does not exist in the dictionary. The wrong case on a letter (capitalized or uncapitalized), a typo and using keys not defined in the dictionary can all cause a KeyError. 

In this blog, you will learn about what the KeyError is, why it occurs, and methods to fix it. Without further ado, let’s get started.

Learn More About Python6 Important Things to Know About Python Functions

 

What Is a KeyError in Python?

KeyError is an exception that occurs when you try to access a key that does not exist in a dictionary. KeyError is a type of LookupError that is raised when a key or index used on a mapping or sequence is invalid.

 

What Causes KeyError in Python?

The official documentation states that KeyError is raised when a mapping key is not found in the set of existing keys. When you see a KeyError, it means that the key you are looking for is not found in the dictionary.

Here are the common causes of KeyErrors in Python.

 

Case sensitivity

Python dictionaries are case-sensitive, meaning that course and Course are two different things. So, if you have a key Course and you try to access it with course, you will get a KeyError. Make sure you are using the correct case when accessing keys in a Python dictionary.

 

Typos

When you try to access a key with the wrong key name, you will get a KeyError. For example, if the dictionary has the key Course and you mistype it as cuorse, you will get a KeyError. So, double-check your key name.

 

Non-existent key

When you try to access a key that has not been defined in the dictionary, you will get a KeyError. For example, if you are trying to access the key email,which is not yet defined in the dictionary, you will get a KeyError.

 

Python KeyError Examples

Let’s define a dictionary with some data and then we’ll see how KeyError is raised by showing the common causes discussed above: typos, non-existent keys and case sensitivity.

person_info = {
    'name': 'Satyam Tripathi',
    'age': 22,
    'city': 'Delhi, Bharat',
    'occupation': 'Freelance Writer',
    'is_student': False
}

Case 1: Let’s say you're trying to access the name key and you mistype it as Name.

person_info = {
    'name': 'Satyam Tripathi',
    'age': 22,
    'city': 'Delhi, Bharat',
    'occupation': 'Freelance Writer',
    'is_student': False
}

print(person_info["Name"])

Here’s the code output:

Traceback (most recent call last):
  File "c:\\Users\\triposat\\test.py", line 9, in <module>
    print(person_info["Name"])
KeyError: 'Name'

Boom! You get an error because Name is not a key in the dictionary.

Case 2: You want to access the occupation key, but you made a typo and tried to access it with the key name ocupation.

person_info = {
    'name': 'Satyam Tripathi',
    'age': 22,
    'city': 'Delhi, Bharat',
    'occupation': 'Freelance Writer',
    'is_student': False
}

print(person_info["ocupation"])

Here’s the code output:

Traceback (most recent call last):
  File "c:\\Users\\triposat\\test.py", line 9, in <module>
    print(person_info["ocupation"])
KeyError: 'ocupation'

Case 3: You are trying to access a key that is not yet defined in the dictionary. For example, you are trying to access the key phone, which is not yet defined in the dictionary.

person_info = {
    'name': 'Satyam Tripathi',
    'age': 22,
    'city': 'Delhi, Bharat',
    'occupation': 'Freelance Writer',
    'is_student': False
}

print(person_info["phone"])

Here’s the code output:

Traceback (most recent call last):
  File "c:\\Users\\triposat\\test.py", line 9, in <module>
    print(person_info["phone"])
KeyError: 'phone'

 

Methods to Fix KeyError in Python

There are a few standard ways to fix KeyError in Python. The best method for you will depend on your specific use case. The ultimate goal is to fix the error. Here, we will discuss two methods: using the in keyword and using a try-except block.

 

How to Fix KeyError Using the in Keyword

You can use the in keyword to check if a key exists in a dictionary. We will use the in keyword with the if/else statement to check if the key exists and return a sample message if it does not.

person_info = {
    'name': 'Satyam Tripathi',
    'age': 22,
    'city': 'Delhi, Bharat',
    'occupation': 'Freelance Writer',
    'is_student': False
}

user_input = input("Enter item to search: ")

if user_input in person_info:
    print(f"Great, item is found. The result for '{user_input}' is: {person_info[user_input]}")
else:
    print(f"Alert, Item not found! Try to search by: name, age, city, occupation, and is_student")

Here’s the code output:

Let’s walk through the code.

  1. First, we have defined a dictionary (person_info) and stored some sample information.
  2. Next, we take the input from the user. The user will enter the key that they want to search for.
  3. Using the in keyword, we search for the user key in the dictionary.
  4. If the key exists, we return the value of that key. Otherwise, we return the key not found message.

 

How to Fix KeyError Using the try-except Block

You can isolate the exception using a try-except block. This method will allow you to catch the KeyError and handle it intelligently. Note: In a try-except block, the try block checks for errors while the except block handles any error found. For example:

person_info = {
    'name': 'Satyam Tripathi',
    'age': 22,
    'city': 'Delhi, Bharat',
    'is_student': False
}

user_input = input("Enter item to search: ")

try:
    print(f"Great, item is found. The result for '{user_input}' is: {person_info[user_input]}")
except KeyError:
    print(f"Alert, Item not found! Try to search by: name, age, city, occupation, and is_student")

Here’s the code output:

Let’s walk through the code.

  1. First, we have defined a dictionary (person_info) and stored some sample information.
  2. Next, we take the input from the user. The user will enter the key that they want to search for.
  3. If there are no errors, the try block will be executed and the value of the key will be returned.
  4. If there are any errors, the except block will be executed and a message will be displayed to the user saying that the key does not exist.

Try-except is a standard way to handle errors in Python because it can handle various types of errors easily and efficiently.

 

How Do You Prevent KeyError in Python?

To prevent errors from the very beginning of the program, you can set the expected output while creating a dictionary. This way, you won’t have to handle common errors such as KeyError in the future. Here, we will discuss two methods: defaultdict() and setdefault().

 

defaultdict()

You can use the defaultdict() function from the collections module to prevent KeyErrors in Python. With defaultdict(), you can specify a default value for keys that do not exist in the dictionary. This method is helpful when you forget to check if a key exists before accessing it, as it will not raise a KeyError. Instead, you will get the default value that you specified.

In the following code, we set the default value to key not found. So, if any key is not found, you will not get a KeyError, but you will get the message key not found.

from collections import defaultdict

# Creating a defaultdict with a default value of "Key not found!"
person_info = defaultdict(lambda: "Key not found!")

# Adding some information to the person_info dictionary
person_info["name"] = "Satyam"
person_info["age"] = 22

# Accessing keys that exist
print(person_info["name"])  # Output: Satyam
print(person_info["age"])   # Output: 30

# Accessing keys that do not exist
print(person_info["city"])  # Output: Key not found!

 

setdefault()

Another method is the setdefault() function. It sets the default value for a key. If the key is already in the dictionary, it returns the existing value. Otherwise, it inserts the key with the default value and returns the default value.

In the following code, the age key is already in the dictionary. We are trying to set the default value for the age key, but this is not possible. So, the age value remains the same, which is 22. We are also trying to set the default value for the city key, which is not in the dictionary. So, the city value is set to the default value, which is Not found. Now, if we try to access the city key, the default value will be printed.

# Create a dictionary
person_info = {"name": "Satyam", "age": 22}

# Using setdefault to access and set a default value for a missing key
age = person_info.setdefault("age", "Not found!")
city = person_info.setdefault("city", "Not found!")

# Magic, key is in the dictionary
print(age) # Output: 22

# key is not in the dictionary
print(city)   # Output: Not found!

Learn More About PythonA Guide to Python Virtual Environments

 

KeyError in Python Fixes: Conclusion

You learned about the KeyError exception in Python. This common error can occur when you try to access a key that is not present in the dictionary.

Video explainer for fixing KeyError in Python. Credit: Analyst Rising / You Tube

So, you should handle it efficiently. By using the methods discussed in this article, you can fix the KeyError and prevent it in the future.

Frequently Asked Questions

KeyError is an exception that occurs when you try to access a key that does not exist in a dictionary.

There are a few standard ways to fix a KeyError in Python. These methods include using the in keyword and using a try-except block.

Hiring Now
Truist
Cloud • Fintech • Other • Payments • Software • Data Privacy
SHARE