A dictionary is a popularly utilized data structure in Python that makes use of mapping. To access values of any given dictionary, we use keys. In some scenarios, programmers get key errors because of the absence of the key that they are trying to access so it is essential for them to resolve key errors to maintain the stability and efficiency of a code.

This write-up will show you how a KeyError occurs in Python and its appropriate solutions.

Python Key Error

A Python KeyError is thrown/encountered when an attempt is made to access a key that is not present/available in the Dictionary. For instance, look at the example shown below:

scores = {'Peter': 21, 'Austin': 35, 'Drew': 41}
scores['John']

In the above code:

  • A dictionary is initialized named “scores”.
  • The code accesses the key Micheal from the scores dictionary.

The output of the above code is as follows:

It can be seen that a KeyError is thrown because the key “Micheal” is not present in the scores dictionary.

How to Resolve/Fix a KeyError in Python?

We can resolve a key error in Python using 2 methods:

  1. Using In Keyword
  2. Using Try-Except Block

Method 1: Use In Keyword to Fix/Resolve Key Error

To fix key errors, the in keyword is commonly used. It displays True if the element to be fetched is available in the dictionary and False otherwise.

Let’s see an example:

employee = {
    "name": "Watson",
    "designation": "Python Developer",
    "pay": 80000
}

Employee_Details = input("What info about the employee do you want? ")

if Employee_Details in employee:
    print(f"The response to your request is {employee[Employee_Details]}")
else:
    print(f"There doesn't exist any parameter with'{Employee_Details}' key. Try inputting name, Designation or pay.")

In the above code:

  • A dictionary is initialized called employee which consists of 3 key items, name, designation, and pay.
  • An input function is created which prompts the user to ask for the information.
  • If the user enters a correct key, that is present in the employee dictionary, the key will be retrieved from the dictionary and displayed on the screen.
  • If the user enters an incorrect key that is not present in the dictionary, the program will tell the user that the given input is wrong and will provide the correct key options.

The output of the above code is as follows:

It can be seen that the provided inputs(name, designation, pay) are correct, so the program is working perfectly. Let’s try out another prompt:

We can see that the incorrect input is provided, so the program says there is no parameter with the age key instead of showing a key error.

Method 2: Use Try-Except to Fix/Resolve Key Error in Python

The try-except method is a crucial method to resolve key errors in a Python Program. The try block looks for any error in the code. If the error exists, it is managed by the except block

employee = {
    "name": "Watson",
    "designation": "Python Developer",
    "pay": 80000
}

Employee_Details = input("What info about the employee do you want? ")

try:
    print(f"The response/reply to your query is {employee[Employee_Details]}")
except KeyError:
    print(f"'{Employee_Details}' key Not found. Try inputting name, Designation or pay.")

In the above code:

  • The first 2 steps are the same as previous.
  • When the try block is executed, it returns the key value. If there is an error, the program will go to the except block
  • The except block manages the error and tells the user that the provided input is wrong.

The output of the above code is as follows:

It can be seen that the provided input is correct, so the program is working perfectly. Let’s specify a key that does not exist in the dictionary, and see how the try-except method deals with it:

We can see that the provided input is wrong so the program says there is no parameter with the employee_id key instead of showing a key error.

Conclusion

We can resolve key errors in Python using two methods. In the first approach, the “in” keyword is implemented, which will retrieve True if the element is present in the dictionary, otherwise False. The second method is by using exception handling(try-except). The try block looks for any error in the code. If the error exists, it is managed by the except block. This guide has demonstrated how to resolve a key error in Python.