Exercise

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.

Instructions

100 XP
  • Safely print 'Union Square Park' from the squirrels_by_park dictionary .
  • Safely print the type of 'Fort Tryon Park' from the squirrels_by_park dictionary.
  • Safely print 'Central Park' from the squirrels_by_park dictionary or 'Not Found'.