Concepts / Tuple Assignment and Unpacking

Tuple Assignment and Unpacking

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

  • Programming

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.

callcontainscontainscontainsDictionary dkey-value entriesd.items()returns item tuples('a', 10)key-value tuple('b', 1)key-value tuple('c', 22)key-value tuple
How does a dictionary's collection of key-value pairs become a sequence of two-item tuples when items() is called?

Assigning Key and Value

python

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.

first elementsecond element('a', 10)two elementskey'a'val10
How are the two values in each key-value tuple assigned to separate variables such as key and val?

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.

First iteration: The tuple ('a', 10) is unpacked. key receives 'a', val receives 10, and the print statement outputs 10 a.

Second iteration: The tuple ('b', 1) is unpacked. key becomes 'b', val becomes 1, and the print statement outputs 1 b.

Third iteration: The tuple ('c', 22) is unpacked. key becomes 'c', val becomes 22, and the print statement outputs 22 c.

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

next itemnext itemno more itemsIteration 1('a', 10) → key='a', val=10Iteration 2('b', 1) → key='b', val=1Iteration 3('c', 22) → key='c', val=22Loop endsall tuples processed
What key-value tuple is selected, unpacked, and processed at each iteration of the for loop?
Output
10 a
1 b
22 c

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

suppliesnext tuplevariables assignedfinish bodyyesnod.items()item tuplesSelect tuplenext itemUnpack tuplekey and valLoop bodyuses current variablesMore tuplescontinue or endLoop endsall items processed
How does control flow move from retrieving dictionary items to assigning variables, executing the loop body, and starting the next iteration?

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)

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

print val, keyprint val, keyprint val, key('a', 10)key='a', val=1010 aprinted line('b', 1)key='b', val=11 bprinted line('c', 22)key='c', val=2222 cprinted line
How does each unpacked key-value pair produce the corresponding line or result in the program's output?

Common Unpacking Mistakes

  • Using only one loop variable when each item contains both a key and a value

    This does not use tuple assignment to place the two elements into separate variables.

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

  • Using more or fewer than two receiving variables

    Each item returned by items() contains one key-value pair, represented as a two-element tuple.

    Fix: Use exactly two variables to match the two elements in each tuple.

  • Reversing the meaning of the variables

    The first tuple element is assigned to the first variable, and the second tuple element is assigned to the second variable.

    Fix: With for key, val in d.items():, key receives the dictionary key and val receives its corresponding value.

  • Assuming the iteration is alphabetical or insertion order

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

    Fix: When tracing output for this pattern, use the stated hash key order rather than assuming alphabetical or insertion order.

A Reliable Tracing Method

  1. List the key-value tuples supplied by items().
  2. Take the first tuple and assign its first element to key and its second element to val.
  3. Read the loop body using those current values.
  4. Record the result produced by the loop body.
  5. Repeat the assignment and processing for the next tuple.
  6. Stop after every tuple has been processed.
MEDIUM

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

  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 unpacks each pair into key and val.
  3. The variables are updated on every iteration before the loop body runs.
  4. To predict output, trace the tuples in their stated hash key order and then apply the loop body to each unpacked pair.
  5. Use exactly two receiving variables when unpacking the key-value tuples returned by items().

Key Takeaways

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