1. Concept library
  2. Python Foundations
  3. Module 5: Dictionaries and sets

Concept

Iterating over dictionaries

Looping over a dict gives its keys; items() gives key and value pairs together, and values() just the values. Dicts keep insertion order.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what looping over a dict, its items() and its values() each gives
  2. Write a loop over items() that builds a new dict from an old one
  3. Spot the RuntimeError from changing a dict while looping over it, and fix it

In practice

A few lines that show Iterating over dictionaries doing its job.

Python
stock = {"apple": 12, "pear": 0, "plum": 4}

for fruit, count in stock.items():
    if count == 0:
        print(fruit, "is sold out")

in_stock = {f: c for f, c in stock.items() if c > 0}
print(in_stock)

The common mistake

Watch for

Adding or deleting keys while looping over the same dict, which raises RuntimeError. Loop over list(stock) or build a new dict instead.

What to know first

Your roadmap puts these before Iterating over dictionaries, unless you already know them.

How it stays learned

Once a session shows you understand Iterating over dictionaries, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Iterating over dictionaries.

Previous in the module← Dictionary lookups
Next in the moduleSets and uniqueness →