建立未知結構的字典
有時候你需要一個結構來保存巢狀資料,但你可能不確定所有的鍵是否都存在。當你想把項目附加到該鍵對應的 list 時,就可能出問題。你或許還記得我們在影片中探索過的 NYC 資料。若要用一般的字典解決這個問題,你需要先測試該鍵是否存在於字典中;如果不存在,就用空的 list 新增它。
你將使用一個紀錄清單,其中包含我們研究中雌性企鵝的物種、翼長、體重,以及性別。下一個練習中,你會用更簡單的方法解決同類型的問題。
本練習屬於課程
Python 的資料型別
練習說明
- 建立一個名為
female_penguin_weights的空字典。 - 迭代
weight_log,並將其解包到變數species、sex和body_mass。 - 檢查
female_penguin_weights字典中是否已存在該物種。如果不存在,就為該物種鍵建立一個空的 list。接著,對於weight_log中的所有項目,將由sex和body_mass組成的 tuple 附加到female_penguin_weights字典中該species鍵底下。 - 印出
female_penguin_weights中物種'Adlie'的內容。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create an empty dictionary: female_penguin_weights
female_penguin_weights = ____
# Iterate over the weight_log entries
for ____, ____, ____ in ____:
# Check to see if species is already in the dictionary
if ____ not in ____:
# Create an empty list for any missing species
female_penguin_weights[species] = ____
# Append the sex and body_mass as a tuple to the species keys list
female_penguin_weights[species].____
# Print the weights for 'Adlie'
print(____)