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.
This exercise is part of the course
Data Types in Python
Exercise instructions
- Import
defaultdict
fromcollections
. - Create a
defaultdict
with a default type oflist
calledmale_penguin_weights
. - Iterate over the list
weight_log
, unpacking it into the variablesspecies
,sex
, andbody_mass
, as you did in the previous exercise. Usespecies
as the key of themale_penguin_weights
dictionary and appendbody_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.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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])