×

python · level 2 · unit 1 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Loop through a dictionary to visit every pair.

A for loop over a dictionary visits each key, in the order the keys were added. Inside the loop, square brackets fetch the value that goes with each key.

Often you want both at once. hands over each key with its value, and a loop with two variables catches them: the key lands in the first, the value in the second.

hands over the values on their own, and adds up a group of numbers. Together they total a whole dictionary in one line.

steps = {"Mon": 4200, "Tue": 6100, "Wed": 5300}
for day, count in steps.items():
    print(f"{day}: {count} steps")
print(f"Total: {sum(steps.values())} steps")

for key in d gives you only the keys, while .items() gives keys and values together.