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