始める無料で始める

キーの値リストへ安全に追加する

辞書を扱うとき、使用する前にデータ型を初期化する必要があることがよくあります。代表的な例はリストで、各キーごとに初期化しておかないと、そのリストに要素を追加できません。

defaultdict を使うと、未初期化の各キーに何を入れるかを定義できます。defaultdict を作成するときは、listtuplesetintstringdictionary など、任意の有効な型オブジェクトを渡します。

前の演習と同じ体重記録を使いますが、今回は調査対象のオスのペンギンに注目します。

この演習はコースの一部です

Python のデータ型

コースを見る

演習の手順

  • collections から defaultdict をインポートします。
  • 既定の型が listdefaultdict を作成し、male_penguin_weights という名前を付けます。
  • リスト weight_log を反復処理し、前の演習と同様に speciessexbody_mass にアンパックします。speciesmale_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])
コードを編集して実行