Due to its ease of use and extensive library support, Python is very popular but it too has its share of errors, commonly made by new learners. One of these errors is called KeyError in Python. We will learn in this article how to ignore and fix this KeyError.
What is a KeyError in Python?
When an error occurs in python, developers refer to it as “throwing an error’. KeyErrors are pretty common errors for beginners.
A KeyError is thrown when a program or code tries to access a key that is not present in a specified dictionary. A dictionary in python is a data structure that stores key-value pairs. Every key is unique and has a value associated with it. When a KeyError is raised, it means that the specified key is not found in the dictionary and therefore the program is unable to retrieve the value associated with it.
Here’s an example of a code that would throw a key error:
my_dict = {'apple': 1, 'banana': 2, 'orange': 3} print(my_dict['grape'])
In the above example, we have created a dictionary called ‘my_dict’ and given it three key-value pairs. We then tried to ask the program to print the value associated with the key ’grape’. Obviously, this would be a source of confusion for the compiler as the key ‘grape’ does not exist. Therefore it raises a KeyError.
How to fix KeyError in Python?
Let's now look at some of the ways to fix the KeyError easily.
The best way to fix KeyError is to Check if the key exists. This can be easily done using the ‘in’ operator. It has a very simple syntax [value in sequence]. Essentially we are checking to figure out if the requested value or key exists in the sequence or dictionary.
Here is an example:
fruits= {'apple': 1, 'banana': 2, 'orange': 3} If 'grape' in fruits: print(fruits['grape']) else: print('Key not found')
Output:
Key not found
This code checks to see if the key "grape" is present in the dictionary "fruits" using an if-else statement. For example, if the key is present in "grape," print "grape," else, print that it is not present. Also, we have a detailed article on how to check if a key exists in a dictionary in Python.
You can also implement the get() method to solve KeyError. The get() method is a simpler way of doing the same thing as the if-else statement, just shorter and written in one line. It has the option of returning a default value that has to be specified by the user after the key name.
Understand it with the following code:
fruits= {'apple': 1, 'banana': 2, ‘orange’: 3} print(fruits.get('grape', 'Key not found’))
Output:
Key not found
In this block of code, we first create a dictionary called ‘fruits’. Then we print the ‘grape’ key from fruits. In case the ‘grape’ key is not present in the dictionary, as is the case, the default response that we have given, ‘Key not found’ is printed for the user to see.
There is one more method to fix KeyError by using the defaultdict class. This class is found in the collections module. If a user attempts to call a key that doesn't exist in a standard dictionary, a key error is raised. Here is an example:
from collections import defaultdict fruits = {'apple': 2, 'banana': 3} d = defaultdict(int) for key in fruits: d[key] = fruits[key] print(d['orange']) for key, value in d.items(): print(key, value)
Output:
0 0 apple 2 orange 0 banana 3
Here, we created a dictionary called "fruits," gave it values, and then added them to the defaultdict after first importing the defaultdict class from the collections module. With the defaultdict, if we try to access a key that doesn't exist, like "orange," we get the value "0" by default. Lastly, we are using a for statement to loop through all of the dictionary's accessible values.
If you still have problems understanding it as a new coder, you can chat with our Python tutors online for instant solutions.
How to Ignore KeyError?
Ignoring coding errors is not advised, especially for novice users, as it can result in unexpected outcomes and the programmed code may metaphorically break down. A try-except block of code will be useful in cases of lengthy codes, where we are left with no other options.
A try-except block is a structure in programming that is used for handling any faults or exceptions that can arise while a program is being executed. The block of code that is placed in the ‘try’ block may or may not contain an error. If the compiler finds no error in the ‘try’ block, it will ignore it and move on as normal.
If there are any errors, the compiler looks at the ‘escape’ block and tries to find if that error has been specified. If it has been specified, the compiler handles the error as per what the user has coded. The following is the syntax:
try:
# code that may raise an exception
except ExceptionType:
# code to handle the exception
And here’s an example:
my_dict = {'apple': 1, 'banana': 2, 'orange': 3} try: print(my_dict['grape']) except KeyError: print('Key not found')
Output:
Key not found
Here, we specify what the compiler should do if the portion of code inside the "try" block has an error. A print statement that we defined will only print if a KeyError occurs. We have specified only a KeyError in the except block. After printing the output of the statement, the compiler will proceed to ignore this block of code and move on to the following block.
Conclusion
In conclusion, a KeyError is a pretty common error to make in python while dealing with dictionaries. Nothing to be embarrassed about, plus it’s pretty simple to fix by either checking if the key exists in the dictionary, using a get() method, or by using the defaultdict class. Happy Learning :)