Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

How to Handle a Python KeyError

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.')

Become a Member to join the conversation.