KeyError Exception in Python

By Lenin Mishra

This is the part of the 9th day in the Python 30 series. Check out the series here.

A KeyError exception is raised when you are trying to access an invalid key in a python dictionary. It tells you that there was an issue retrieving the key you were trying to access. It is part of the LookupError Exception class.

Example 1

Code

pylenin_info = {'name': 'Lenin Mishra',
                'age': 28,
                'language': 'Python'}
user_input = input('What do you want to learn about Pylenin==> ')

if user_input:
    print(f'{user_input} is {pylenin_info[user_input]}')
else:
    print(f'{user_input} is unknown')

The above code uses input() function and f-strings. Check them out.

Output

What do you want to learn about Pylenin==> wife
Traceback (most recent call last):
  File "some_file_location", line 7, in <module>
    print(f'{user_input} is {pylenin_info[user_input]}')
KeyError: 'wife'

As you can see, when you are trying to access an unavailable key, Python throws you a KeyError. You can handle this error using the KeyError Exception class in Python.

Example 2 - Handling KeyError in Python

Code

pylenin_info = {'name': 'Lenin Mishra',
                'age': 28,
                'language': 'Python'}
user_input = input('What do you want to learn about Pylenin==> ')

try:
    print(f'{user_input} is {pylenin_info[user_input]}')
except KeyError as e:
    print(f'{e}, {e.__class__}')

Output

What do you want to learn about Pylenin==> wife
'wife', <class 'KeyError'>

Check out other Python Built-in Exception classes in Python.

  1. Try, Except, Else and Finally in Python
  2. ZeroDivisionError Exception in Python
  3. OverflowError Exception in Python
  4. ArithmeticError Exception in Python
  5. IndexError Exception in Python
  6. LookupError Exception in Python
  7. StopIteration Exception in Python
  8. TypeError Exception in Python
  9. NameError Exception in Python
  10. FileNotFoundError Exception in Python
  11. Catch Multiple Exceptions in Python