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.
Questo esercizio fa parte del corso
Data Types in Python
Istruzioni dell'esercizio
- Import
defaultdictfromcollections. - Create a
defaultdictwith a default type oflistcalledmale_penguin_weights. - Iterate over the list
weight_log, unpacking it into the variablesspecies,sex, andbody_mass, as you did in the previous exercise. Usespeciesas the key of themale_penguin_weightsdictionary and appendbody_massto its value. - Print the first 2 items of the
male_penguin_weightsdictionary. You can use the.items()method for this. Remember to make it a list.
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
# 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])