Iterating Over Dictionary Keys
The items() method returns a sequence of tuples, where each tuple contains one key-value pair from the dictionary.
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)
The 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
Assuming the loop is alphabetical or insertion ordered
The source describes dictionary iteration here as occurring in hash key order. That order depends on how the implementation stores keys internally.
Fix:
When tracing this pattern, use the stated hash key order rather than assuming alphabetical or insertion order.Assigning the value to key and the key to val
Each tuple places the key first and the corresponding value second.
Fix:
Read the assignment from left to right: key receives the first tuple element, and val receives the second.Using the wrong number of variables
Each tuple returned by items() contains exactly one key-value pair, so it has two elements.
Fix:
Use two variables, such as key and val, to match the two-element tuple.Predicting output from variable names instead of the print statement
The output order is controlled by the arguments in the print statement.
Fix:
Trace 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 |
Predict Before Running
What do you think happens?
What output does this loop produce?
Reveal answer
Answer: 10 a 1 b 22 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
- The items() method returns a sequence of two-element tuples, with one key-value pair in each tuple.
- In for key, val in d.items():, tuple assignment puts the key in key and the value in val.
- The loop updates key and val for every iteration until all tuples have been processed.
- The print statement determines the order in which the key and value appear in the output.
- For this topic, trace dictionary entries in hash key order rather than assuming alphabetical or insertion order.
Key Takeaways
- 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.