Iterating Over Dictionary Keys
The items() method returns a sequence of tuples. Each tuple contains one dictionary key-value pair.
Why Process Both Parts
When you iterate through a dictionary, you may need both the key and its corresponding value. For example, a report may need to show each name with its score, or a calculation may need both pieces of information. The items() method provides both at the same time, so you do not need to iterate over keys and look up each value separately.
The items() method returns a sequence of tuples. Each tuple contains one dictionary key-value pair.
The Loop Header
This loop header combines three ideas. The for loop visits each tuple returned by d.items(). The tuple assignment key, val unpacks the tuple into two variables. The first element goes into key, and the second element goes into val. On each iteration, both variables are updated to the next key-value pair.
Tracing Each Pair
d = {'a': 10, 'b': 1, 'c': 22}
for key, val in d.items():
print(val, key)- 1Before the loop begins,
d.items()produces the tuples ('a', 10), ('b', 1), and ('c', 22). - 2On the first iteration, key receives 'a' and val receives 10. The loop prints 10 a.
- 3On the second iteration, key becomes 'b' and val becomes 1. The loop prints 1 b.
- 4On the third iteration, key becomes 'c' and val becomes 22. The loop prints 22 c.
- 5After the third iteration, there are no more tuples, so the loop ends.
- The dictionary contains three key-value entries.
d.items()supplies one two-element tuple for each entry.- key receives the key and val receives the corresponding value.
- The print statement displays val first and key second.
10 a
1 b
22 cThe print statement uses val before key, so each output line shows the value first and the key second. The variables do not keep their first assignments; they are updated on every iteration.
From Entry to Output
Each tuple follows the same path. First, items() makes the key-value pair available to the loop. Next, tuple assignment places the first tuple element in key and the second in val. Finally, the loop body uses those variables. In the source example, print(val, key) reverses the display order, but the assignments themselves remain key first and value second.
Order and Unpacking Mistakes
Common mistake Assuming the loop is alphabetical or insertion ordered
What it looks likeTreating the output order as guaranteed to be alphabetical or as the order in which entries were added
Why it failsThe source describes dictionary iteration here as occurring in hash key order. That order depends on how the implementation stores keys internally.
Do this insteadWhen tracing this pattern, use the stated hash key order rather than assuming alphabetical or insertion order.
Common mistake Assigning the value to key and the key to val
What it looks likefor key, val in d.items(): followed by treating key as the valueWhy it failsEach tuple places the key first and the corresponding value second.
Do this insteadRead the assignment from left to right: key receives the first tuple element, and val receives the second.
Common mistake Using the wrong number of variables
What it looks likeTrying to unpack each items() tuple into one variable or more than two variables
Why it failsEach tuple returned by
items()contains exactly one key-value pair, so it has two elements.Do this insteadUse two variables, such as key and val, to match the two-element tuple.
Common mistake Predicting output from variable names instead of the print statement
What it looks likeExpecting key to be printed before val because key appears first in the loop header
Why it failsThe output order is controlled by the arguments in the print statement.
Do this insteadTrace the assignments first, then read the print statement in its actual order.
| Part of the pattern | Role |
|---|---|
| d.items() | Provides a sequence of key-value tuples |
| key, val | Unpacks each two-element tuple into two variables |
| for | Processes one tuple on each iteration |
| print(val, key) | Uses the variables and displays the value before the key |
How the parts of a dictionary item-iteration loop work together
Predict Before Running
What do you think happens?
What output does this loop produce?
Reveal answer
10 a1 b22 c
items() supplies ('a', 10), ('b', 1), and ('c', 22). Tuple assignment places each key in key and each value in val. The print statement uses val first and key second.
Trace the loop in three columns: the tuple supplied by items(), the values assigned to key and val, and the text printed by the loop body. Use the dictionary entries in the stated hash key order.
Hints
- Each item is a two-element tuple.
- The first element goes to key and the second goes to val.
- Read the print arguments in their written order.
Pattern Summary
- 1The
items()method returns a sequence of two-element tuples, with one key-value pair in each tuple. - 2In for key, val in
d.items():, tuple assignment puts the key in key and the value in val. - 3The loop updates key and val for every iteration until all tuples have been processed.
- 4The print statement determines the order in which the key and value appear in the output.
- 5For this topic, trace dictionary entries in hash key order rather than assuming alphabetical or insertion order.
At a glance
- Use
items()when a loop needs both dictionary keys and values. - Tuple assignment automatically unpacks each key-value tuple into two variables.
- Trace each iteration by identifying the current tuple, its assignments, and the loop body's output.
- Use the print statement to determine output order, and account for the stated hash key order.