3.3. Nesting

Sometimes you'll want to store multiple dictionaries in a list, or a list of items as a value in a dictionary. These actions are called nesting. We will look at some examples.

A List of Dictionaries

Let say we want to make dictionaries of an ice cream shop that sells different kind of ice creams. After defining the dictionaries for each ice cream, we builds a list consists of those items.

Let's add a variable order consisting of ice creams ID and see how to get the price and name of the food from your order:

A List in a Dictionary

It is sometimes useful to put a list inside a dictionary. Say we have different ice cream with different flavors. Rather than making a new variable, we can put the flavor in a list:

A Dictionary in a Dictionary

Rather than making multiple variables for each ice cream, you can make another dictionary consisting of the ice cream types and their attributes.

Notice that the structure of each user's dictionary is identical. This structure makes nested dictionaries easier to work with. If each user's dictionary had different keys, the code inside the for loop would be more complicated.

Exercise 3.3

  1. Pets
    -
    Make several dictionaries, where each dictionary represents a different pet.In each dictionary, include the kind of animal and the owner's name.
    - Store these dictionaries in a list called pets.
    - Next, loop through your list and as you do, print everything you know about each pet.


  1. Favorite Places
    Make a dictionary called favorite_places. Think of three people names to use as keys in the dictionary, and store one to three favorite places for each person. Loop through the dictionary, and print each person's name and their favorite places.


  1. Cities
    Make a dictionary called cities. Use the names of three cities as keys in your dictionary. Create a dictionary of information about each city and include the country that the city is in and its approximate population. The values for each city's dictionary should be country and population. Print the name of each city and all of the information you have stored about it.