The KeyError exception is typically raised when a key is not found in a dictionary. This is in the case when we  try to access a dictionary value with a key that does  not exist.

ExampleEdit & Run
D = {1: 'One', 2: "Two", 3: "Three"}

print(D[2])
print(D[3])

#A key Error is raised
print(D[4])
copy
Output:
Two Three Traceback (most recent call last):   File "<string>", line 7, in <module> KeyError: 4 [Finished in 0.010468193795531988s]

The KeyError exception is derived from the LookupError exception. LookupError exceptions usually occur when trying to access a key or index that does not exist in a collection data type. 

ExampleEdit & Run
print(issubclass(KeyError, LookupError))
copy
Output:
True [Finished in 0.01012118300423026s]

Handling KeyError

We can use the usual try-catch blocks to handle KeyError exceptions.

ExampleEdit & Run
D = {"Japan": "Tokyo", "Finland": "Helsinki", "Kenya": "Nairobi"}

try:
    print(D["Kenya"])
    print(D["Japan"])
    print(D["America"])

except KeyError:
     print("The value given is not in the dictionary")
copy
Output:
Nairobi Tokyo The value given is not in the dictionary [Finished in 0.013028162065893412s]

Avoid the KeyError exception

The dict class defines the get() method which works similarly to using square brackets. The difference is that the get() method returns None if the key given is not found in the dictionary instead of raising a KeyError. We can also pass a second argument which will be returned instead of None if the lookup fails.

Syntax:
D.get(k, default = None)
copy

Where parameter represents the key and parameter default is the default value that will be returned. If the default argument it  is not given, None is returned.

ExampleEdit & Run
D = {"Japan": "Tokyo", "Finland": "Helsinki", "Kenya": "Nairobi"}


print(D.get("Kenya"))
print(D.get("Japan"))
print(D.get("America"))
print(D.get("Canada", "Ottawa"))
copy
Output:
Nairobi Tokyo None Ottawa [Finished in 0.010056613013148308s]