1. Learn
  2. /
  3. Courses
  4. /
  5. Data Types in Python

Connected

Exercise

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.

Instructions

100 XP
  • 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'.