BaşlayınÜcretsiz Başlayın

Creating dictionaries of an unknown structure

Occasionally, you'll need a structure to hold nested data, and you may not be certain that the keys will all actually exist. This can be an issue if you're trying to append items to a list for that key. You might remember the NYC data that we explored in the video. In order to solve the problem with a regular dictionary, you'll need to test that the key exists in the dictionary, and if not, add it with an empty list.

You'll be working with a list of entries that contains species, flipper length, body mass, and sex of the female penguins in our study. You're going to solve this same type of problem with a much easier solution in the next exercise.

Bu egzersiz

Data Types in Python

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • Create an empty dictionary called female_penguin_weights.
  • Iterate over weight_log, unpacking it into the variables species, sex, and body_mass.
  • Check to see if the species already exists in the female_penguin_weights dictionary. If it does not exist, create an empty list for the species key. Then, append a tuple consisting of sex and body_mass to the species key of the female_penguin_weights dictionary for all entries in the weight_log.
  • Print the female_penguin_weights for 'Adlie'.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# Create an empty dictionary: female_penguin_weights
female_penguin_weights = ____

# Iterate over the weight_log entries
for ____, ____, ____ in ____:
    # Check to see if species is already in the dictionary
    if ____ not in ____:
        # Create an empty list for any missing species
        female_penguin_weights[species] = ____
    # Append the sex and body_mass as a tuple to the species keys list
    female_penguin_weights[species].____
    
# Print the weights for 'Adlie'
print(____)
Kodu Düzenle ve Çalıştır