处理嵌套的混合类型
之前,我们使用 in 表达式来判断数据是否在字典中,例如 if 'cookies' in recipes_dict。但是,如果我们想在某个键对应的是"由字典组成的列表"的情况下查找数据该怎么办?在这种情形下,您可以使用 for 循环遍历嵌套列表中的各个项并进行操作。此外,我们还能利用列表推导式来高效筛选嵌套的字典列表。例如:[cookie for cookie in recipes["cookies"] if "chocolate chip" in cookie["name"]] 将返回 recipes 列表中,name 键里包含 chocolate chip 的 cookie 列表。
我们已经加载了一个 squirrels_by_park 字典,其中键为公园名称,值为松鼠信息构成的字典列表。
本练习是课程的一部分
Python 的数据类型
练习说明
- 使用 for 循环遍历
squirrels_by_park中Tompkins Square Park键下的松鼠:- 安全地打印每只松鼠的活动信息。
- 使用列表推导式,打印在
Union Square Park中primary_fur_color为'Cinnamon'的松鼠列表。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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 "____" ____ ____["____"]])