Get startedGet started for free

Dealing with nested dictionaries

A dictionary can contain another dictionary as the value of a key, and this is a very common way to deal with repeating data structures such as yearly, monthly or weekly data. All the same rules apply when creating or accessing the dictionary.

For example, if you had a dictionary that had a ranking of my cookie consumption by year and type of cookie. It might look like cookies = {'2017': {'chocolate chip': 483, 'peanut butter': 115}, '2016': {'chocolate chip': 9513, 'peanut butter': 6792}}. I could access how many chocolate chip cookies I ate in 2016 using cookies['2016']['chocolate chip'].

When exploring a new dictionary, it can be helpful to use the .keys() method to get an idea of what data might be available within the dictionary. You can also iterate over a dictionary and it will return each key in the dictionary for you to use inside the loop.

We've loaded a squirrels_by_park dictionary with park names for the keys and a nested dictionary of one squirrels data.

This exercise is part of the course

Data Types in Python

View Course

Exercise instructions

  • Print the keys of the squirrels_by_park dictionary, NOTE: They are park_names.
  • Print the keys of the squirrels_by_park dictionary for the park_name Union Square Park.
  • Loop over the squirrels_by_park dictionary.
    • Inside the loop, safely print the park_name and the highlights_in_fur_color. Print 'N/A' if the highlightsinfur_color is not found or None.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Print a list of keys from the squirrels_by_park dictionary
print(____)

# Print the keys from the squirrels_by_park dictionary for 'Union Square Park'
print(____)

# Loop over the dictionary
for park_name in squirrels_by_park:
    # Safely print the park_name and the highlights_in_fur_color or 'N/A'
    print(park_name, squirrels_by_park[____].____('____', '____'))
Edit and Run Code