Dealing with nested mixed types
Previously, we used the in
expression so see if data is in a dictionary such as if 'cookies' in recipes_dict
. However, what if we want to find data in a dictionary key that is a list of dictionaries? In that scenario, we can use a for loop to loop over the items in the nested list and operate on them. Additionally, we can leverage list comprehensions to effectively filter nested lists of dictionaries. For example: [cookie for cookie in recipes["cookies"] if "chocolate chip" in cookie["name"]]
would return a list of cookies in recipes list that have chocolate chip in the name key of the cookie.
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
Exercise instructions
- Use a for loop to iterate over the squirrels found in the
Tompkins Square Park
key ofsquirrels_by_park
:- Safely print each activities of each squirrel.
- Print the list of
'Cinnamon'
primary_fur_color
squirrels found inUnion Square Park
using a list comprehension.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Use a for loop to iterate over the squirrels in Tompkins Square Park:
for squirrel in ____["____"]:
# Safely print the activities of each squirrel or None
print(____.____("____"))
# Print the list of 'Cinnamon' primary_fur_color squirrels in Union Square Park
print([squirrel for squirrel in ____["____"] if "____" ____ ____["____"]])