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.
This exercise is part of the course
Data Types in Python
Exercise instructions
- Create an empty dictionary called
female_penguin_weights
. - Iterate over
weight_log
, unpacking it into the variablesspecies
,sex
, andbody_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 ofsex
andbody_mass
to thespecies
key of thefemale_penguin_weights
dictionary for all entries in theweight_log
. - Print the
female_penguin_weights
for'Adlie'
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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(____)