Safely finding by key
As demonstrated in the video, if you attempt to access a key that isn't present in a dictionary, you'll get a KeyError
. One option to handle this type of error is to use a try: except:
block. You can learn more about error handling in Python Data Science Toolbox (Part 1).
Python provides a faster, more versatile tool to help with this problem in the form of the .get()
method. The .get()
method allows you to supply the name of a key, and optionally, what you'd like to have returned if the key is not found.
You'll be using same squirrels_by_park
dictionary, which is keyed by the park name and the value is a tuple with the main color, highlights, action, and reaction to humans, and will gain practice using the .get()
method.
This exercise is part of the course
Data Types in Python
Exercise instructions
- Safely print
'Union Square Park'
from thesquirrels_by_park
dictionary . - Safely print the type of
'Fort Tryon Park'
from thesquirrels_by_park
dictionary. - Safely print
'Central Park'
from thesquirrels_by_park
dictionary or'Not Found'
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Safely print 'Union Square Park' from the squirrels_by_park dictionary
print(____.____(____))
# Safely print the type of 'Fort Tryon Park' from the squirrels_by_park dictionary
print(____(squirrels_by_park.____('Fort Tryon Park')))
# Safely print 'Central Park' from the squirrels_by_park dictionary or 'Not Found'
print(____.get(____, ____))