Iterating Over Dictionary Values
The standard pattern is for key, val in d.items():. The two loop variables receive the key and value from each dictionary entry.
Why Retrieve Both Parts
When iterating through a dictionary, you may need both parts of each entry: the key and its corresponding value. For example, a report may need to display a name together with a score. Python provides the items() method so a loop can receive both pieces directly instead of iterating over keys and looking up each value separately.
The standard pattern is for key, val in d.items():. The two loop variables receive the key and value from each dictionary entry.
The Items Collection
The items() method returns a sequence of tuples. Each tuple contains one key-value pair from the dictionary. For a dictionary with entries for a, b, and c, the sequence can be represented as ('a', 10), ('b', 1), ('c', 22). Each tuple has exactly two elements: the key first and the corresponding value second.
Unpacking the Loop Header
for key, val in d.items():
print(val, key)- 1The for keyword begins the iteration.
- 2The names key and val are assigned from the two elements of the current tuple.
- 3The in keyword connects the loop variables to the sequence produced by
d.items(). - 4The loop body executes once for each key-value tuple.
- key and val are two loop variables.
d.items()supplies one two-element tuple at a time.- The tuple is unpacked so key receives the key and val receives the value.
- The loop body can use both variables.
Tuple assignment happens automatically in the loop header. The first tuple element goes to key, and the second tuple element goes to val.
Tracing Each Iteration
Following the Three Pairs
Trace the loop for d = {'a': 10, 'b': 1, 'c': 22} and determine what print(val, key) produces.
- 1First iteration
The tuple ('a', 10) is unpacked. key receives 'a' and val receives 10, so the loop prints 10 a.
- 2Second iteration
The tuple ('b', 1) is unpacked. key becomes 'b' and val becomes 1, so the loop prints 1 b.
- 3Third iteration
The tuple ('c', 22) is unpacked. key becomes 'c' and val becomes 22, so the loop prints 22 c.
- 4Completion
There are no more items, so the loop ends after three iterations.
The output is 10 a, then 1 b, then 22 c, with each result on its own printed line.
10 a
1 b
22 cPredicting the Printed Values
What do you think happens?
What does the loop print when the items are processed as ('a', 10), ('b', 1), and ('c', 22)?
Reveal answer
10 a, then 1 b, then 22 c
Each tuple is unpacked with the key first and the value second. The print statement uses val first and key second, so each value appears before its key.
Before reading the reveal, trace the tuple ('b', 1) through the loop. Write down the new values of key and val, then determine the order in which print(val, key) displays them.
Hints
- The first tuple element is assigned to key.
- The second tuple element is assigned to val.
- The print statement places val before key.
Mistakes with Items
Common mistake Using only one loop variable for items() when you need both parts of each pair.
What it looks likefor entry in d.items():Why it failsEach item is a two-element tuple, so one variable receives the whole tuple rather than separate key and value variables.
Do this insteadUse two variables: for key, val in d.items():
Common mistake Reversing the meaning of the unpacked variables.
What it looks likefor val, key in d.items():Why it failsThe first tuple element is the key and the second tuple element is the value.
Do this insteadUse names that match the tuple positions: for key, val in d.items():
Common mistake Assuming the output must be alphabetical or insertion-ordered.
What it looks likeExpecting the loop to process 'a', then 'b', then 'c' because those keys look alphabetical.
Why it failsThe source example describes the iteration order as hash key order, determined by how the implementation stores keys internally.
Do this insteadUse the stated hash key order when tracing the source example, rather than assuming another ordering.
Common mistake Printing the variables in the wrong order when predicting output.
What it looks likePredicting a 10 when the loop body is print(val, key).
Why it failsThe loop assigns key first and val second, but the print call places val first.
Do this insteadTrace both assignment order and print argument order separately.
The Idiomatic Pattern
Use for key, val in d.items() when the loop body needs both a dictionary key and its corresponding value. This pattern combines the items() method, tuple assignment, and a for loop in one direct operation. It is cleaner and more efficient than iterating over keys and looking up each value separately.
On every iteration, key and val are updated to the next key-value pair in hash order. The loop body then works with the current pair before the next pair is unpacked.
Key Takeaways
- 1The
items()method returns a sequence of two-element tuples containing dictionary keys and values. - 2In for key, val in
d.items():, tuple assignment unpacks each tuple automatically. - 3The first tuple element is assigned to key, and the second is assigned to val.
- 4Each loop iteration updates the variables to the next key-value pair and then runs the loop body.
- 5When tracing the source example, use its stated hash key order rather than assuming alphabetical or insertion order.
At a glance
items()provides dictionary entries as key-value tuples.- Tuple assignment in the loop header separates each tuple into key and val.
- The loop variables are updated on every iteration before the loop body runs.
- To predict output, trace the tuple order, the assignments, and the order of arguments in print.
- The source example describes dictionary iteration as following hash key order.