MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Data Types in Python

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# 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 dan Jalankan Kode