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.
Questo esercizio fa parte del corso
Data Types in Python
Istruzioni dell'esercizio
- Check to see if
Tompkins Square Parkis in thesquirrels_by_parkdictionary, and print'Found Tompkins Square Park'if it is present. - Check to see if
Central Parkis insquirrels_by_park. Then, print'Found Central Park'if found and'Central Park missing'if not found.
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
# 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')