Concepts / Iterating Over Dictionary Keys

Iterating Over Dictionary Keys

The items() method returns a sequence of tuples, where each tuple contains one key-value pair from the dictionary.

  • Programming

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.

containscontainscontainsitems()items()items()ddictionarya: 10key-value entry('a', 10)two-element tupleb: 1key-value entry('b', 1)two-element tuplec: 22key-value entry('c', 22)two-element tuple
How does dictionary key-value data become a sequence of two-element tuples returned by items()?

The Loop Header

python

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.

forstarts iterationkeyfirst tuple element,separates variablesvalsecond tuple elementintakes values fromd.items()key-value tuples
How are the two elements of each items() tuple assigned to the key and value variables?

Tracing Each Pair

d = {'a': 10, 'b': 1, 'c': 22} for key, val in d.items(): print(val, key)

next tuplenext tuplenext tuplefinishedd.items()three tuplesIteration 1key='a', val=10Loop endsno tuples remainIteration 2key='b', val=1Iteration 3key='c', val=22
What happens next in the loop, and which key-value pair is processed on each iteration?

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

items() suppliesvariables usedprints('a', 10)dictionary itemkey='a', val=10tuple assignmentprint(val, key)output statement10 aprinted line
How does each dictionary entry move through items(), tuple unpacking, and the output statement?

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 patternRole
d.items()Provides a sequence of key-value tuples
key, valUnpacks each two-element tuple into two variables
forProcesses 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?

  • 10 a, then 1 b, then 22 c
  • a 10, then b 1, then c 22
  • 10 b, then 1 c, then 22 a
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.

MEDIUM

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

  1. The items() method returns a sequence of two-element tuples, with one key-value pair in each tuple.
  2. In for key, val in d.items():, tuple assignment puts the key in key and the value in val.
  3. The loop updates key and val for every iteration until all tuples have been processed.
  4. The print statement determines the order in which the key and value appear in the output.
  5. 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.