키의 값 리스트에 안전하게 추가하기
사전(dictionary)으로 작업할 때는, 사용하기 전에 데이터 타입을 초기화해야 하는 경우가 자주 있어요. 대표적인 예가 리스트인데, 어떤 키에 값을 추가(append)하려면 그 키에 리스트가 먼저 초기화되어 있어야 합니다.
defaultdict를 사용하면 초기화되지 않은 각 키에 무엇을 넣을지 미리 정할 수 있어요. defaultdict를 만들 때 list, tuple, set, int, string, dictionary 같은 타입이나 다른 유효한 타입 객체를 전달합니다.
이전 연습 문제와 같은 체중 기록을 사용하지만, 이번에는 연구에 포함된 수컷 펭귄 데이터로 작업할 거예요.
이 연습은 강의의 일부입니다
Python의 데이터 타입
연습 안내
collections에서defaultdict를 임포트하세요.- 기본 타입이
list인defaultdict를 만들어male_penguin_weights라고 이름 지으세요. - 리스트
weight_log를 순회하면서 이전 연습 문제처럼species,sex,body_mass로 언패킹하세요.species를male_penguin_weights사전의 키로 사용하고, 그 값 리스트에body_mass를 추가하세요. male_penguin_weights사전의 처음 2개 항목을 출력하세요. 이를 위해.items()메서드를 사용할 수 있어요. 리스트로 변환하는 것도 잊지 마세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Import defaultdict
____
# Create a defaultdict with a default type of list: male_penguin_weights
male_penguin_weights = ____
# Iterate over the weight_log entries
for ____, ____, ____ in ____:
# Use the species as the key, and append the body_mass to it
____
# Print the first 2 items of the male_penguin_weights dictionary
print(____(____)[:2])