Looping Through Dictionaries and Nested Data

A for loop goes through a dictionary's keys, items(), keys() and values() give its pairs, its keys or its values, and lists of dictionaries and dictionaries of lists hold whole tables of data, the shape CSV files and web APIs give you.

Apprentice · Python · Updated

By

After this lesson you can

  • Loop through a dictionary's keys, values and pairs with keys(), values() and items()
  • Read and loop through nested data, a list of dictionaries and a dictionary of lists

Key takeaways

  • A for loop over a dictionary goes through its keys, in the order they were added.
  • items() gives each key with its value, so a loop such as for ingredient, amount in pantry.items() names both halves of every pair.
  • keys() gives only the keys and values() only the values, so sum(prices.values()) adds up every value.
  • A list of dictionaries is a table with one dictionary per row, and a dictionary of lists files a whole list under each key.
  • recipes[0]["name"] reads in two steps, left to right, first the row and then the value under "name" in it.

Sooner or later you need every entry in a dictionary, not one: a report of the whole pantry, the total of a shopping trip, every product in a store's catalog. And real data is rarely one dictionary on its own. A spreadsheet's rows, a CSV file and the answer from a web API arrive as dictionaries inside lists, or lists inside dictionaries. This lesson shows how to loop through a dictionary, and how to read data that's nested, one collection inside another.

The example is Pantry Pal, a recipe app: its pantry, a shopping trip's receipt and a box of recipes.

Looping through a dictionary

A dictionary stores values under keys: in {"eggs": 6, "flour": 4}, the value 6 is stored under the key "eggs", and pantry["eggs"] reads it. Printing a pantry by hand takes one print() per key, and every new ingredient needs a new line of code. A for loop goes through them all instead. Looping over a dictionary gives you its keys:

pantry = {"eggs": 6, "flour": 4, "milk": 2}

for ingredient in pantry:
    print(ingredient, pantry[ingredient])
eggs 6
flour 4
milk 2

The keys come in the order they were added, and pantry[ingredient] reads each one's value. That works, and there's a neater way to get both at once.

items(), keys() and values()

The .items() method gives the dictionary's key-value pairs, one pair at a time. Two names after for, with a comma between them, give each pair's two halves a name: the key first, then the value.

pantry = {"eggs": 6, "flour": 4, "milk": 2}

for ingredient, amount in pantry.items():
    print(f"{ingredient}: {amount}")
eggs: 6
flour: 4
milk: 2

Read the loop line aloud as "for each ingredient and its amount in the pantry's items". When you need only one side, .keys() gives the keys and .values() gives the values. Here's the receipt from a shopping trip:

prices = {"eggs": 3.49, "flour": 2.99, "milk": 3.79}

print(list(prices.keys()))
print(round(sum(prices.values()), 2))
print(max(prices.values()))
['eggs', 'flour', 'milk']
10.27
3.79

list() turns the keys into a plain list for printing, while sum() and max() take the values as they are. Adding up prices can leave a tiny rounding error in the last decimal place, so the total is rounded to cents with round(..., 2).

A list of dictionaries: rows of a table

Pantry Pal's recipe box has a name, a cooking time and a number of servings for each recipe. Picture it as a table: one row per recipe, one column per detail. In Python, each row is a dictionary, and the table is a list of them. A list holds values in order inside square brackets, and it counts from 0, so recipes[0] is its first item:

recipes = [
    {"name": "Pancakes", "minutes": 20, "servings": 4},
    {"name": "Omelet", "minutes": 10, "servings": 1},
    {"name": "Banana bread", "minutes": 65, "servings": 8},
]

print(recipes[0]["name"])
for recipe in recipes:
    if recipe["minutes"] <= 30:
        print(recipe["name"], "takes", recipe["minutes"], "minutes")
Pancakes
Pancakes takes 20 minutes
Omelet takes 10 minutes

recipes[0]["name"] reads in two steps, left to right: recipes[0] is the first row, a dictionary, and ["name"] reads the value under "name" in it. In the loop, each recipe is one whole row.

![A list of dictionaries drawn as a table: the list recipes holds three dictionaries, one per row, with the columns name, minutes and servings; recipes[0] points at the first row, and recipes0]["name"] points at the cell Pancakes in it

This is nested data: collections inside a collection. It's the shape you'll meet everywhere. Python can read each row of a CSV file as a dictionary, and the JSON a web API sends back usually becomes a list of dictionaries.

A dictionary of lists

The nesting can go the other way. Each recipe's ingredients make a list, and a dictionary files each list under the recipe's name. .append() adds an item to the end of a list:

ingredients = {
    "Pancakes": ["eggs", "flour", "milk"],
    "Omelet": ["eggs", "cheese"],
}

print(ingredients["Omelet"])
ingredients["Omelet"].append("spinach")
for name, needed in ingredients.items():
    print(name, "needs", len(needed), "ingredients")
['eggs', 'cheese']
Pancakes needs 3 ingredients
Omelet needs 3 ingredients

ingredients["Omelet"] is a whole list, so a list's tools work on it: .append(), len(), in. Which shape fits? A list of dictionaries when you have many records with the same details, like rows; a dictionary of lists when you look up a group by its name.

Do it: list the quick recipes

Pantry Pal has a quick dinner button. It shows only the recipes that are ready in the time you have.

  • recipes: a list of dictionaries, one per recipe, each with a "name" and the "minutes" it takes.
  • max_minutes: the most minutes you have.

Your job: write the function quick_recipes(recipes, max_minutes) so it returns a list of the names of the recipes that take max_minutes or less.

  • The names come in the same order as the recipes in the list.
  • A recipe that takes exactly max_minutes counts.
  • When no recipe fits, it returns an empty list, [].

Worked through: the recipes are Pancakes (20 minutes), Omelet (10 minutes) and Banana bread (65 minutes), and you have 30 minutes. 20 is 30 or less, 10 is 30 or less, and 65 isn't, so quick_recipes(recipes, 30) returns ["Pancakes", "Omelet"].

Practiced live on the lesson page: write the Python right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

Almost all real data is nested, rows of records or groups of lists, and a loop with .items() or two steps of square brackets is how you get at any piece of it.

Key terms

Related