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.
Bu egzersiz
Data Types in Python
kursunun bir parçasıdırEgzersiz talimatları
- Safely print
'Union Square Park'from thesquirrels_by_parkdictionary . - Safely print the type of
'Fort Tryon Park'from thesquirrels_by_parkdictionary. - Safely print
'Central Park'from thesquirrels_by_parkdictionary or'Not Found'.
Uygulamalı interaktif egzersiz
Bu örnek kodu tamamlayarak bu egzersizi bitirin.
# 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(____, ____))