Tuple Assignment and Unpacking
The loop pattern for key, val in d.items(): combines a dictionary method, a for loop, and tuple unpacking in one statement.
Why Both Parts Matter
When a loop works with a dictionary, you may need both parts of each entry: the key and its corresponding value. Python provides a direct pattern for this task. Calling items() provides key-value pairs, and tuple assignment separates each pair into two variables during the loop.
The loop pattern for key, val in d.items(): combines a dictionary method, a for loop, and tuple unpacking in one statement.
From Dictionary Entries to Tuples
The items() method returns a sequence of tuples. Each tuple contains one key-value pair from the dictionary. For a dictionary whose entries are represented by the pairs ('a', 10), ('b', 1), and ('c', 22), the items are the three two-item tuples ('a', 10), ('b', 1), and ('c', 22). The first item in each tuple is the key, and the second item is its value.
Assigning Key and Value
The names key and val are two separate variables. On each iteration, Python takes the next two-item tuple returned by d.items() and unpacks it. The first element is assigned to key, and the second element is assigned to val. The variable names are chosen by the programmer; their important role here is their position in the assignment.
Tracing Every Iteration
Following Three Dictionary Items
Trace the loop for the item tuples ('a', 10), ('b', 1), and ('c', 22). Determine the values assigned to key and val and the line printed at each iteration.
- 1First iteration
The tuple ('a', 10) is unpacked. key receives 'a', val receives 10, and the print statement outputs 10 a.
- 2Second iteration
The tuple ('b', 1) is unpacked. key becomes 'b', val becomes 1, and the print statement outputs 1 b.
- 3Third iteration
The tuple ('c', 22) is unpacked. key becomes 'c', val becomes 22, and the print statement outputs 22 c.
- 4Loop completion
After the third item has been processed, there are no more item tuples for the loop to process.
The loop prints 10 a, then 1 b, then 22 c, with each pair appearing on its own output line.
10 a
1 b
22 cFollowing the Control Flow
The loop follows a repeated sequence. First, d.items() supplies the collection of key-value tuples. The for loop selects the next tuple. Tuple assignment unpacks that tuple into key and val. The loop body runs using those current variable values. Control then returns to the loop so the next tuple can be selected and unpacked. When all tuples have been processed, the loop ends.
Predicting the Printed Results
What do you think happens?
The item tuples are ('a', 10), ('b', 1), and ('c', 22). What does this loop print?
for key, val in d.items():
print(val, key)Reveal answer
It prints 10 a, then 1 b, then 22 c, with each pair on its own line.
The first tuple element is assigned to key and the second tuple element is assigned to val. The print statement places val before key, so each value appears before its key.
Common Unpacking Mistakes
Common mistake Using only one loop variable when each item contains both a key and a value
What it looks likefor item in d.items():Why it failsThis does not use tuple assignment to place the two elements into separate variables.
Do this insteadUse two variables, such as for key, val in d.items():.
Common mistake Using more or fewer than two receiving variables
What it looks likefor key, val, extra in d.items():Why it failsEach item returned by
items()contains one key-value pair, represented as a two-element tuple.Do this insteadUse exactly two variables to match the two elements in each tuple.
Common mistake Reversing the meaning of the variables
What it looks likeTreating val as the key and key as the value
Why it failsThe first tuple element is assigned to the first variable, and the second tuple element is assigned to the second variable.
Do this insteadWith for key, val in d.items():, key receives the dictionary key and val receives its corresponding value.
Common mistake Assuming the iteration is alphabetical or insertion order
Why it failsThe source material describes the iteration order as hash key order, determined by how the dictionary implementation stores keys internally.
Do this insteadWhen tracing output for this pattern, use the stated hash key order rather than assuming alphabetical or insertion order.
A Reliable Tracing Method
- 1List the key-value tuples supplied by
items(). - 2Take the first tuple and assign its first element to key and its second element to val.
- 3Read the loop body using those current values.
- 4Record the result produced by the loop body.
- 5Repeat the assignment and processing for the next tuple.
- 6Stop after every tuple has been processed.
Trace a loop whose item tuples are ('a', 10), ('b', 1), and ('c', 22). For each iteration, write down the current values of key and val, then write the result of print(val, key).
Hints
- The first tuple element goes to key.
- The second tuple element goes to val.
- The print statement places val before key.
Core Takeaways
- 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 unpacks each pair into key and val. - 3The variables are updated on every iteration before the loop body runs.
- 4To predict output, trace the tuples in their stated hash key order and then apply the loop body to each unpacked pair.
- 5Use exactly two receiving variables when unpacking the key-value tuples returned by
items().
At a glance
items()provides dictionary entries as two-element key-value tuples.- Tuple assignment separates each tuple into variables such as key and val.
- A for loop repeats the unpacking and processing for every dictionary item.
- Output prediction requires tracking the current key, current value, and the order of the item tuples.
- The source pattern describes dictionary iteration order as hash key order.