🎓 A1Learner
🔍

Python Loop Dictionaries

A dictionary loop walks the keys, the values, or the pairs of a dictionary. A dictionary holds pairs, not single items.

Loop over keys by default

No method is needed. The loop gives each key in turn.

phone = {"Ada": "111", "Bob": "222", "Cy": "333"}
for name in phone:
    print(name)

Loop over values

The .values() method gives each value in turn.

phone = {"Ada": "111", "Bob": "222", "Cy": "333"}
for number in phone.values():
    print(number)

Loop over pairs with .items()

Each pair splits into name and number. This split is pair unpacking.

phone = {"Ada": "111", "Bob": "222", "Cy": "333"}
for name, number in phone.items():
    print(name, number)

Check membership while looping

The word in tests a key. It works inside a loop too.

phone = {"Ada": "111", "Bob": "222", "Cy": "333"}
wanted = ["Bob", "Eve"]
for name in wanted:
    if name in phone:
        print(name, "is listed")
    else:
        print(name, "is missing")

Example

phone = {"Ada": "111", "Bob": "222", "Cy": "333", "Dee": "444"}
for name, number in phone.items():
    print(f"{name}: {number}")

Key points

  • Use for with a dictionary to loop over its keys.
  • Keys come out in insertion order.
  • Insertion order: the order you added the pairs.
  • Use .values() to loop over the values only.
  • Use .items() to loop over key and value pairs.
  • Pair unpacking: for name, number in ... splits each pair into two variables.
  • Use in inside a loop to check if a key is in the dictionary.
  • Write .values() or .items() when you need more than keys.

In this example, phone holds four names and numbers. The loop uses .items() to get each pair. Pair unpacking puts the key in name. It puts the value in number. The f-string prints the name, a colon, and the number. The lines come out in insertion order.

Note

Looping gives keys by default.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does for name in phone: loop over by default?