Exercise

Safely appending to a key's value list

Often when working with dictionaries, you will need to initialize a data type before you can use it. A prime example of this is a list, which has to be initialized on each key before you can append to that list.

A defaultdict allows you to define what each uninitialized key will contain. When establishing a defaultdict, you pass it the type you want it to be, such as a list, tuple, set, int, string, dictionary or any other valid type object.

You'll be working with the same weight log as last exercise, but with the male penguins in our study.

Instructions

100 XP
  • Import defaultdict from collections.
  • Create a defaultdict with a default type of list called male_penguin_weights.
  • Iterate over the list weight_log, unpacking it into the variables species, sex, and body_mass, as you did in the previous exercise. Use species as the key of the male_penguin_weights dictionary and append body_mass to its value.
  • Print the first 2 items of the male_penguin_weights dictionary. You can use the .items() method for this. Remember to make it a list.