Concepts / Iterating Over Dictionary Keys

Iterating Over Dictionary Keys

The items() method returns a sequence of tuples. Each tuple contains one dictionary key-value pair.

  • 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.

Key point

The items() method returns a sequence of tuples. Each tuple contains one dictionary key-value pair.

ddictionarya: 10key-value entry('a', 10)two-element tupleb: 1key-value entry('b', 1)two-element tuplec: 22key-value entry('c', 22)two-element tuplecontainscontainscontainsitems()items()items()
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

Code walkthrough
d = {'a': 10, 'b': 1, 'c': 22}

for key, val in d.items():
    print(val, key)
  1. 1
    Before the loop begins, d.items() produces the tuples ('a', 10), ('b', 1), and ('c', 22).
  2. 2
    On the first iteration, key receives 'a' and val receives 10. The loop prints 10 a.
  3. 3
    On the second iteration, key becomes 'b' and val becomes 1. The loop prints 1 b.
  4. 4
    On the third iteration, key becomes 'c' and val becomes 22. The loop prints 22 c.
  5. 5
    After 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.
Output
10 a
1 b
22 c
d.items()three tuplesIteration 1key='a', val=10Loop endsno tuples remainIteration 2key='b', val=1Iteration 3key='c', val=22next tuplenext tuplenext tuplefinished
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

('a', 10)dictionary itemkey='a', val=10tuple assignmentprint(val, key)output statement10 aprinted lineitems() suppliesvariables usedprints
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

  • Common mistake

    Assuming the loop is alphabetical or insertion ordered

    What it looks like

    Treating the output order as guaranteed to be alphabetical or as the order in which entries were added

    Why it fails

    The source describes dictionary iteration here as occurring in hash key order. That order depends on how the implementation stores keys internally.

    Do this instead

    When 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 like
    for key, val in d.items(): followed by treating key as the value
    Why it fails

    Each tuple places the key first and the corresponding value second.

    Do this instead

    Read 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 like

    Trying to unpack each items() tuple into one variable or more than two variables

    Why it fails

    Each tuple returned by items() contains exactly one key-value pair, so it has two elements.

    Do this instead

    Use 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 like

    Expecting key to be printed before val because key appears first in the loop header

    Why it fails

    The output order is controlled by the arguments in the print statement.

    Do this instead

    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

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?

  • 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 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.

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

Related concepts

More concepts starting with I