Concepts / Iterating Over Dictionary Values

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.

  • Programming

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.

Key point

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.

('a', 10)key: 'a'; value: 10('b', 1)key: 'b'; value: 1('c', 22)key: 'c'; value: 22next itemnext item
What structure does items() provide to the loop?

Unpacking the Loop Header

Code walkthrough
for key, val in d.items():
    print(val, key)
  1. 1
    The for keyword begins the iteration.
  2. 2
    The names key and val are assigned from the two elements of the current tuple.
  3. 3
    The in keyword connects the loop variables to the sequence produced by d.items().
  4. 4
    The 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.
forstarts iterationkey, valreceive two tuple elementsinconnects variables to itemsd.items()supplies key-value tuplesintroducesassigned fromreads
How does one tuple containing a key and value become two loop variables?
Key point

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

python
('a', 10)key = 'a'; val = 1010 aprinted output('b', 1)key = 'b'; val = 11 bprinted output('c', 22)key = 'c'; val = 2222 cprinted outputLoop endsprint(val, key)next iterationprint(val, key)next iterationprint(val, key)after three iterations
What happens next as the loop retrieves each key-value pair and executes the loop body?
Worked example

Following the Three Pairs

Trace the loop for d = {'a': 10, 'b': 1, 'c': 22} and determine what print(val, key) produces.

  1. 1
    First iteration

    The tuple ('a', 10) is unpacked. key receives 'a' and val receives 10, so the loop prints 10 a.

  2. 2
    Second iteration

    The tuple ('b', 1) is unpacked. key becomes 'b' and val becomes 1, so the loop prints 1 b.

  3. 3
    Third iteration

    The tuple ('c', 22) is unpacked. key becomes 'c' and val becomes 22, so the loop prints 22 c.

  4. 4
    Completion

    There are no more items, so the loop ends after three iterations.

Result

The output is 10 a, then 1 b, then 22 c, with each result on its own printed line.

Output
10 a
1 b
22 c

Predicting 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)?

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

('a', 10)key 'a'; value 1010 avalue then key('b', 1)key 'b'; value 11 bvalue then key('c', 22)key 'c'; value 2222 cvalue then keyprint(val, key)print(val, key)print(val, key)
How does each dictionary item map to the values printed during successive loop iterations?
EASY

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 like
    for entry in d.items():
    Why it fails

    Each item is a two-element tuple, so one variable receives the whole tuple rather than separate key and value variables.

    Do this instead

    Use two variables: for key, val in d.items():

  • Common mistake

    Reversing the meaning of the unpacked variables.

    What it looks like
    for val, key in d.items():
    Why it fails

    The first tuple element is the key and the second tuple element is the value.

    Do this instead

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

    Expecting the loop to process 'a', then 'b', then 'c' because those keys look alphabetical.

    Why it fails

    The source example describes the iteration order as hash key order, determined by how the implementation stores keys internally.

    Do this instead

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

    Predicting a 10 when the loop body is print(val, key).

    Why it fails

    The loop assigns key first and val second, but the print call places val first.

    Do this instead

    Trace both assignment order and print argument order separately.

The Idiomatic Pattern

Best practice

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.

Key point

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

  1. 1
    The items() method returns a sequence of two-element tuples containing dictionary keys and values.
  2. 2
    In for key, val in d.items():, tuple assignment unpacks each tuple automatically.
  3. 3
    The first tuple element is assigned to key, and the second is assigned to val.
  4. 4
    Each loop iteration updates the variables to the next key-value pair and then runs the loop body.
  5. 5
    When 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.

Related concepts

More concepts starting with I