處理巢狀且混合型別的資料
先前我們使用 in 運算子來檢查某筆資料是否在字典中,例如 if 'cookies' in recipes_dict。但是,如果我們想在某個鍵的值是一個「字典所組成的清單」裡找資料該怎麼辦?這種情況下,可以用 for 迴圈逐一走訪巢狀清單中的各項目並加以處理。此外,也能運用串列生成式(list comprehension)有效篩選巢狀的字典清單。例如:[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 "____" ____ ____["____"]])