IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Data Types in Python

Visualizza il corso

Istruzioni dell'esercizio

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

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

# 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(____, ____))
Modifica ed esegui il codice