Python keyerror exception – How do you Handle the KeyError Exception In Python?

Python keyerror exception: The KeyError exception in Python is a common one that learners run into. Knowing why a KeyError can occur and how to prevent it from terminating your program are key steps in becoming a better Python programmer.

What is a KeyError  Exception?

Python try except keyerror: When you try to access a key that isn’t in a dictionary, a Python KeyError exception is thrown.

The KeyError is raised when a mapping key is accessed but not found in the mapping, according to Python’s official documentation. A data structure that maps one set of values to another is known as mapping. The dictionary is the most popular mapping in Python.

The Python KeyError exception is a form of LookupError that indicates that getting the key you were looking for was unsuccessful. The semantic meaning of a KeyError is that the key that was being looked for could not be found.

Example

gvn_dictnry= {'hello': 10, 'this': 20, 'is': 30, 'btechgeeks':40}
print(gvn_dictnry['Python'])

Output:

KeyError Traceback (most recent call last)
<ipython-input-2-76ba687a0c7e> in <module>()
1 gvn_dictnry= {'hello': 10, 'this': 20, 'is': 30, 'btechgeeks':40}
----> 2 print(gvn_dictnry['Python'])

KeyError: 'Python'

Explanation:

Here there is no key 'Python' in the given dictionary, so, it raises a KeyError exception when 
we tried to access it.

Handling the KeyError Exception in Python

keyerror exception python: The exceptions that are thrown, while irritating at first, are readily handled using exception handling procedures. There are two ways to handle the KeyError Exception:

Method #1: Stopping the exception from occurring

a)Using get() method:

When you don’t want to add the missing key-value pair to the dictionary but also don’t want an error to arise, you can use the get() method.
If the key cannot be found, this function returns the given default value. If no default is given, it will fall back to None by default.

Example1

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Add some random key-value pair to the given dictionary using the get() method and store it in another variable.
  • Here the get method handles the KeyError Exception
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dictnry= {'hello': 10, 'this': 20, 'is': 30}
# Add some random key-value pair to the given dictionary using the get() method
# and store it in another variable.
# Here the get method handles the KeyError Exception
rslt = gvn_dictnry.get('btechgeeks', 40)
# Print the above result
print(rslt)

Output:

40

Here, the Key ‘btechgeeks’ does not exist. However, you prevent the program from throwing exceptions by calling the get() function and setting the default value to 40.

Example2

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Give some random key name as user input and store it in another variable.
  • Call the get method by passing the key to the get() function and store the result in the same dictionary variable.
  • The Exit of the Program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dictnry= {'hello': 10, 'this': 20, 'is': 30, 'btechgeeks':40}
# Give some random key name as user input and store it in another variable.
userkey = input('Enter some random key: ')
#Call the get method by passing the key to the get() function and store the result in the same dictionary variable 
gvn_dictnry = gvn_dictnry.get(userkey)
if gvn_dictnry:
    print(f'He choosed {userkey} key.')
else:
    print(f"{userkey} key is not present in the dictionary")

Output:

Enter some random key: python 
python key is not present in the dictionary

b)Using setdefault() Method:

When you don’t want an exception to occur and want to add the missing key-value pair to the dictionary but don’t want an exception to occur, you can use the setdefault() method. It is pretty similar to the procedure described previously. This technique, on the other hand, adds value to the dictionary.

Example

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Add some random key-value pair to the given dictionary using the setdefault() method
    and store it in another variable.
  • Here the setdefault() method handles the KeyError Exception and
    if the key is not present in the dictionary then it sets the default value.
  • Print the above result.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dictnry= {'hello': 10, 'this': 20, 'is': 30}
# Add some random key-value pair to the given dictionary using the setdefault() method
# and store it in another variable.
# Here the setdefault() method handles the KeyError Exception and
# if the key is not present in the dictionary then it sets the default value
rslt = gvn_dictnry.setdefault('btechgeeks', 40)
# Print the above result
print(rslt)

Output:

40

Method #2: Catching the exception and working on it further

You may not be able to catch the exception in some instances. In such a circumstance, you can just log the exception details and use it to rectify the issue later. You are now aware that anytime you encounter an exception, you may view all relevant information in the traceback.
However, if the software fails, you will lose this data. As a result, you can log this information using the try and except clause.

Approach:

  • Import traceback module using the import keyword.
  • Handling the KeyError Exception using the try-except blocks
  • Give the dictionary as static input and store it in a variable.
  • Print some random key-value that is not present in the given dictionary
  • Check if the KeyError occurs using the except block and handle if it occurs
  • Print some random text to handle it
  • Print the Exception using the print_exc() function of the traceback module.
  • The Exit of the Program.

Below is the implementation:

# Import traceback module using the import keyword.
import traceback
# Handling the KeyError Exception using the try-except blocks
try:
  # Give the dictionary as static input and store it in a variable.
  gvn_dictnry= {'hello': 10, 'this': 20, 'is': 30}
  # Print some random key-value that is not present in the given dictionary
  print(gvn_dictnry['btechgeeks'])
# Check if the KeyError occurs using the except block and handle if it occurs
except KeyError as error:
  # Print some random text to handle it
  print("The specified key is not present in the given dictionary:", error)
  print()
  # Print the Exception using the print_exc() function of the traceback module
  traceback.print_exc()

Output:

The specified key is not present in the given dictionary: 'btechgeeks'

Traceback (most recent call last):
File "<ipython-input-6-86d83443ad76>", line 8, in <module>
print(gvn_dictnry['btechgeeks'])
KeyError: 'btechgeeks'

The code statements that can result in an error have been placed under try in this case. If an exception occurs, the except clause will catch it, and you can then assign the exception object to a variable (error). Using this variable, you can later print the exception information. The traceback.print_exc() method prints the stack trace, which can be used to locate the Exception object.