Concepts / For Loops and Iteration in Python

For Loops and Iteration in Python

The .items() method returns tuples of (key, value) pairs from a dictionary.

  • Programming

The Missing Half of a Dictionary Loop

A dictionary stores information as key-value pairs. When you write a basic loop such as for item in d:, the loop gives you the dictionary's keys. That is not enough when the loop body also needs each key's corresponding value. The .items() method solves this problem by providing both parts of each dictionary entry together.

What .items() Produces

The .items() method returns tuples containing a key and its value. For the dictionary d = {'a': 10, 'b': 1, 'c': 22}, calling d.items() provides the three pairs ('a', 10), ('b', 1), and ('c', 22). Each pair keeps the key connected to its corresponding value, so a loop can process both pieces during the same iteration.

.items().items().items()a10('a', 10)b1('b', 1)c22('c', 22)
What does the dictionary's data look like before iteration, and what pairs does .items() provide?
python

Unpacking Each Pair

In for key, val in d.items():, the two variable names on the left match the two parts of each tuple returned by .items(). Tuple unpacking happens automatically. On each iteration, the key goes into key and the value goes into val. The variable names are chosen by the programmer; what matters is that two variables receive the two parts of each pair.

first elementsecond element('b', 1)one .items() resultkey'b'val1
How does each key-value tuple become two separate variables during a loop iteration?

for key, val in d.items(): print(val, key)

Tracing the Output

What do you think happens?

Predict the three output lines before reading the reveal. The loop uses d = {'a': 10, 'b': 1, 'c': 22} and print(val, key).

Reveal answer

Answer: 10 a 1 b 22 c

The first pair is ('a', 10), so key is 'a' and val is 10. The second pair is ('b', 1), so key is 'b' and val is 1. The third pair is ('c', 22), so key is 'c' and val is 22. Because the print statement places val before key, each line shows the value first.

next iterationnext iteration('a', 10)10 a('b', 1)1 b('c', 22)22 c
What happens on each iteration, and what output does the loop produce?
Output
10 a
1 b
22 c

Reading the loop one iteration at a time

Determine the values of key and val, then determine the printed line for each pair in d = {'a': 10, 'b': 1, 'c': 22}.

First pair: The tuple is ('a', 10). Unpacking assigns key = 'a' and val = 10. The statement print(val, key) produces 10 a.

Second pair: The tuple is ('b', 1). Unpacking assigns key = 'b' and val = 1. The statement print(val, key) produces 1 b.

Third pair: The tuple is ('c', 22). Unpacking assigns key = 'c' and val = 22. The statement print(val, key) produces 22 c.

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

Choosing an Iteration Method

Python dictionaries provide .keys(), .values(), and .items() for different iteration needs. Iterating with .keys() gives the keys, iterating with .values() gives the values, and iterating with .items() gives key-value pairs. Select the method that matches the information required by the loop body.

Iteration expressionLoop variable containsUse it when
d.keys()A keyThe loop needs only keys
d.values()A valueThe loop needs only values
d.items()A key-value pairThe loop needs both keys and values
d.keys()keyd.values()valued.items()key and value
What does the loop receive when it iterates over keys, values, or key-value pairs?
python

Mistakes Beginners Make

  • Expecting a basic dictionary loop to provide both pieces of an entry

    A basic dictionary loop gives you only the keys, so item does not automatically contain the corresponding value.

    Fix: Use for key, val in d.items(): when the loop needs both the key and its value.

  • Using .keys() when the loop also needs values

    This iteration supplies keys only.

    Fix: Use .items() and unpack each pair into two variables.

  • Forgetting that tuple unpacking assigns two separate variables

    The loop does not place the whole pair into one variable. It assigns the pair's first element to key and second element to val.

    Fix: Trace the current tuple first, then assign its key and value to the matching variables.

  • Predicting the print order from the loop header instead of the print statement

    The loop variables are named key and val, but the print statement places val before key.

    Fix: After unpacking, read the output statement from left to right.

Practice Before Running

EASY

Predict the output of this loop before running it. Identify the tuple processed on each iteration, the values assigned to key and val, and the order in which print displays them. scores = {'red': 8, 'blue': 3} for key, val in scores.items(): print(key, val)

Hints
  • Each iteration receives one key-value pair from .items().
  • The first tuple element is assigned to key and the second to val.
  • This print statement places key before val.

Checking the prediction

For scores = {'red': 8, 'blue': 3}, determine the output of for key, val in scores.items(): print(key, val).

First iteration: The current pair is ('red', 8), so key is 'red' and val is 8. The print statement places them in the order red 8.

Second iteration: The current pair is ('blue', 3), so key is 'blue' and val is 3. The print statement places them in the order blue 3.

The predicted output is red 8 followed by blue 3.

Key Takeaways

  1. The .items() method returns key-value tuples from a dictionary.
  2. The pattern for key, val in d.items(): automatically unpacks each tuple into two variables.
  3. A basic loop over a dictionary gives keys, while .keys(), .values(), and .items() let you choose keys, values, or both.
  4. To predict output, process one tuple at a time, assign its two elements, and then read the print statement in order.

Key Takeaways

  • Use .items() when a loop needs both the key and its corresponding value.
  • Each result from .items() is a two-element tuple that Python unpacks into the variables named in the for statement.
  • Use .keys() for keys only, .values() for values only, and .items() for both.
  • Predict dictionary-loop output by tracing each key-value tuple and then following the order used by the loop body.