Concepts / Iterating Over Dictionaries: keys(), values(), and items()

Iterating Over Dictionaries: keys(), values(), and items()

The important transformation is dictionary data into a list whose elements are two-element tuples: one key followed by its corresponding value.

  • Programming
Interactive lab

Try it: What a for Loop Hands You

What a Python for loop gives its loop variable from each kind of iterable: the characters of a string, the positions from range(len(word)), the elements of a list, (index, item) pairs from enumerate(), the numbers of range(start, stop, step), a dict's keys, its .values() and its .items() tuples unpacked into key, val, the inner lists of a nested list and the values an inner loop visits; and why removing items from a list while looping over it skips the next item, while looping over a copy nums[:] does not.

How it works

  1. The for statement asks the object for an iterator, then calls next() on it once per pass.
  2. Each next() result is bound to the loop variable (a tuple result such as ('a', 10) or (0, 'red') is unpacked into two names), and the indented body runs once with it.
  3. A string gives characters, a list gives element values (not positions), range() computes start, start + step, … stopping before stop, and a dict gives its keys in insertion order (.values() the values, .items() key-value tuples).
  4. A nested list's inner list is one element of the outer loop; a second, inner for loop is needed to visit the values inside it.
  5. A list iterator only remembers a position number into the live list: removing an item shifts the later items left, so the item that slides into the passed position is skipped. Looping over a copy (nums[:]) keeps the positions fixed.
  6. When next() has nothing left the loop ends (StopIteration) and the loop variable keeps its last value; an empty iterable runs the body zero times.

Default run (10 steps): A 3-line program. Step through it: each pass of the for loop asks the iterator for its next item, binds the loop variable to it and runs the indented body once. … Done: the loop body ran 3 times. Output: red | green | blue.

Simplified: The programs are twelve fixed templates: you choose the loop and edit only its data (a short string, list items that are words or integers, key: value pairs with word keys and integer values, range numbers from -20 to 20, up to 4 rows of integers, up to 10 numbers). Nothing you type is executed: the lab's own small parsers turn it into literals, and a model of CPython's iterator protocol written for these loops runs the program. Every program was also run in CPython 3.12 under sys.settrace, and the lab reproduces the variables before every line, the printed output, the final variables and the error.

Educational simulation

Loading the simulation…

From Mappings to Tuples

A dictionary stores relationships between keys and values. The items() method is useful when you need to work with both parts of every relationship at the same time. In the tuple-based form, each key-value relationship becomes one tuple, and the collection of those tuples can be stored as a list.

Key point

The important transformation is dictionary data into a list whose elements are two-element tuples: one key followed by its corresponding value.

Tracing the Transformation

Dictionaryb → 2; a → 1; c → 3items()key-value pairsList(b, 2), (a, 1), (c, 3)extract pairslist conversion
How does a dictionary containing several mappings become a collection of tuples while preserving each key-value relationship?

What do you think happens?

Suppose keys are added in the order b, a, c. In what order will the key-value tuples appear?

  • Alphabetical order: a, b, c

  • Insertion order: b, a, c

Reveal answer
Answer:

Insertion order: b, a, c

The tuples are returned in the order the keys were added to the dictionary, not in alphabetical order.

The visual shows the central idea: the dictionary's key-value relationships are preserved, but their representation changes. After conversion to a list, every element is a tuple containing one complete relationship.

Inside Each Pair

Item tuple(key, value)Keyindex 0Valueindex 1first elementsecond element
What does one key-value tuple contain, and where are the key and value positioned?
Definition

An item tuple contains exactly two elements: the key at index 0 and the value at index 1.

The two positions have fixed roles. Index 0 identifies which dictionary key is being represented, while index 1 contains that key's corresponding value. The tuple is immutable, so once the tuple has been created, its two-element structure cannot be changed.

Worked example

Reading One Item

Interpret the tuple (apple, 5) as one dictionary item.

  1. 1
    First position

    The element at index 0 is apple, so apple is the key.

  2. 2
    Second position

    The element at index 1 is 5, so 5 is the value associated with apple.

  3. 3
    Relationship

    Together, the tuple represents one complete key-value relationship.

Result

The tuple contains exactly two elements: key apple at index 0 and value 5 at index 1.

Choosing the Right View

keys()keys aloneKeysvalues()values aloneValuesitems()keys and values togetherKey-value tuplesfocuses onfocuses onkeeps together
How do the three dictionary methods differ in the information they focus on?
MethodInformation emphasizedUseful when
keys()Keys aloneYou need the identifying parts of the dictionary relationships
values()Values aloneYou need the stored results without the keys
items()Each key together with its valueYou need to process or store complete key-value relationships

The key distinction is whether you need keys, values, or both together.

Order of Returned Items

bfirst addedasecond addedcthird addedTuple order(b, 2), (a, 1), (c, 3)thenthenitems() preserves order
In what sequence do key-value pairs appear when items() is used?
Worked example

Predicting the Pair Sequence

A dictionary is built by adding the keys b, a, and c in that order. What tuple order should you expect after converting its items to a list?

  1. 1
    Record the insertion sequence

    The keys were added in the order b, then a, then c.

  2. 2
    Keep each relationship together

    Each key remains paired with its corresponding value in a two-element tuple.

  3. 3
    Apply the ordering rule

    The tuple sequence follows insertion order rather than alphabetical order.

Result

The pairs appear in b, a, c order. They are not rearranged into a, b, c order.

Storing and Iterating Pairs

Dictionary itemskey-value pairsPair 1(key, value)Pair 2(key, value)Tuple liststored for later usefirst pairnext paircollectcollect
How does iteration receive each key-value tuple, and how can those tuples be collected for later use?

When a dictionary's items are iterated, the useful unit is one complete tuple at a time. Because the tuple has a predictable two-element structure, its key and value can be handled together. Converting with list(d.items()) creates an actual list that can be stored, printed, or passed to a function.

EASY

Consider a dictionary whose keys were inserted in the order mango, apple, zebra. Describe the tuple sequence produced by list(d.items()), and identify the key and value positions within any one tuple.

Hints
  • Use insertion order, not alphabetical order.
  • The key is at index 0 and the value is at index 1.
  • Each tuple contains exactly two elements.
  • Common mistake

    Assuming items are returned alphabetically.

    What it looks like

    Expecting apple, mango, zebra merely because that is alphabetical order.

    Why it fails

    The tuples follow the order in which the keys were added.

    Do this instead

    Track insertion order. Sort the resulting list separately only when alphabetical order is required.

  • Common mistake

    Treating an item tuple as if it contained only a key or only a value.

    What it looks like

    Reading (apple, 5) as one value instead of a pair.

    Why it fails

    Every item tuple contains both parts of one key-value relationship.

    Do this instead

    Read index 0 as the key and index 1 as the value.

  • Common mistake

    Assuming an item tuple can be changed after it is created.

    What it looks like

    Trying to replace one element inside a returned tuple.

    Why it fails

    The tuples returned by items() are immutable.

    Do this instead

    Treat each tuple as a fixed representation of its key-value relationship.

  • Common mistake

    Forgetting to create a list when a stored list is required.

    What it looks like

    Using the items result when a function or storage step specifically requires an actual list.

    Why it fails

    list(d.items()) is the operation identified for converting the dict_items object into an actual list.

    Do this instead

    Use list(d.items()) when you need a list that can be stored, printed, or passed to a function.

Key Takeaways

  1. 1
    items() is the choice when both keys and values must remain together.
  2. 2
    The list form contains one two-element tuple for each key-value relationship.
  3. 3
    Within each tuple, the key is at index 0 and the value is at index 1.
  4. 4
    Tuple order follows dictionary insertion order, not alphabetical order.
  5. 5
    Use list(d.items()) when an actual list is needed for storage, printing, or passing to a function.

At a glance

  • items() keeps each key paired with its corresponding value.
  • Each item is an immutable tuple containing exactly two elements.
  • The key occupies index 0 and the value occupies index 1.
  • Items appear in insertion order rather than alphabetical order.
  • list(d.items()) produces an actual list of tuples for storage or further use.

Related concepts

More concepts starting with I