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.
D = {1: 'One', 2: "Two", 3: "Three"}
print(D[2])
print(D[3])
#A key Error is raised
print(D[4])
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.
print(issubclass(KeyError, LookupError))
Handling KeyError
We can use the usual try-catch blocks to handle KeyError
exceptions.
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")
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.
D.get(k, default = None)
Where parameter k
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.
D = {"Japan": "Tokyo", "Finland": "Helsinki", "Kenya": "Nairobi"}
print(D.get("Kenya"))
print(D.get("Japan"))
print(D.get("America"))
print(D.get("Canada", "Ottawa"))