KeyError Exception in Python
Handle Key error in Python using the try-except block.

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.
built-in-exception-classes - Pylenin
A programmer who aims to democratize education in the programming world and help his peers achieve the career of their dreams.
