IniziaInizia gratis

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

Visualizza il corso

Istruzioni dell'esercizio

  • 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.

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])
Modifica ed esegui il codice