When you encounter a KeyError
, there are a few standard ways to handle it. Depending on your use case, some of these solutions might be better than others. The ultimate goal is to stop unexpected KeyError
exceptions from being raised. The usual solution is to use .get()
:
# ages.py
ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
person = input('Get age for: ')
age = ages.get(person, 0)
if age:
print(f'{person} is {age} years old.')
else:
print(f"{person}'s age is unknown.")
Another solution is to check for keys. There are times when you need to determine the existence of a key in a dictionary:
# parse_api_response.py
...
# Assuming you got a `response` from calling an API that might
# have an error key in the `response` if something went wrong
if 'error' in response:
... # Parse the error state
else:
... # Parse the success state
A more general solution is to go with try
and except
to isolate potential exception-raising code and provide a solution:
# ages.py
ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
person = input('Get age for: ')
print(f'{person} is {ages[person]} years old.')