Get startedGet started for free

Checking dictionaries for data

You can check to see if a key exists in a dictionary by using the in expression.

For example, you can check to see if 'cookies' is a key in the recipes dictionary by using if 'cookies' in recipes: this allows you to safely react to data being present in the dictionary.

We've loaded a squirrels_by_park dictionary with park names for the keys and a list of dictionaries of the squirrels.

This exercise is part of the course

Data Types in Python

View Course

Exercise instructions

  • Check to see if Tompkins Square Park is in the squirrels_by_park dictionary, and print 'Found Tompkins Square Park' if it is present.
  • Check to see if Central Park is in squirrels_by_park. Then, print 'Found Central Park' if found and 'Central Park missing' if not found.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Check to see if Tompkins Square Park is in squirrels_by_park
if "____" ____ ____:
    # Print 'Found Tompkins Square Park'
    print('Found Tompkins Square Park')
    
# Check to see if Central Park is in squirrels_by_park
if "____" ____ ____:
    # Print 'Found Central Park' if found
    print('Found Central Park')
else:
    # Print 'Central Park missing' if not found
    print('Central Park missing')
Edit and Run Code