開始使用免費開始

安全地將元素加入鍵對應的清單

在處理字典時,你常常需要先初始化某種資料型別才能使用它。最典型的例子是清單,必須在每個鍵上先初始化清單,之後才能把值加到該清單中。

defaultdict 讓你定義每個尚未初始化的鍵在第一次使用時應該包含什麼。建立 defaultdict 時,你會傳入想要的型別,例如 listtuplesetintstringdictionary,或任何其他有效的型別物件。

你將會使用與上一個練習相同的體重紀錄,但這次聚焦於研究中的公企鵝。

本練習屬於課程

Python 的資料型別

檢視課程

練習說明

  • collections 匯入 defaultdict
  • 建立一個預設型別為 list、名稱為 male_penguin_weightsdefaultdict
  • 迭代清單 weight_log,如同上一個練習,將每筆資料解包到變數 speciessexbody_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])
編輯並執行程式碼