중첩된 혼합 타입 다루기
이전에 if 'cookies' in recipes_dict처럼 in 표현식을 사용해 딕셔너리에 데이터가 있는지 확인했어요. 그런데 딕셔너리 키의 값이 ‘딕셔너리들의 리스트’라면 어떻게 찾을 수 있을까요? 이때는 for 루프를 사용해 중첩된 리스트의 항목을 순회하며 처리할 수 있어요. 또한 리스트 컴프리헨션을 활용하면 중첩된 딕셔너리 리스트를 효과적으로 필터링할 수 있습니다. 예를 들어 [cookie for cookie in recipes["cookies"] if "chocolate chip" in cookie["name"]]는 이름(name) 키에 chocolate chip이 포함된 쿠키만 recipes 리스트에서 골라 새로운 리스트로 돌려줍니다.
parks의 키로 공원 이름이, 값으로는 다람쥐들의 딕셔너리 리스트가 들어 있는 squirrels_by_park 딕셔너리를 불러왔습니다.
이 연습은 강의의 일부입니다
Python의 데이터 타입
연습 안내
squirrels_by_park의Tompkins Square Park키에 있는 다람쥐들을 for 루프로 순회하세요:- 각 다람쥐의 활동(activities)을 안전하게 출력하세요.
- 리스트 컴프리헨션을 사용해
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 "____" ____ ____["____"]])