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.
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
- The for statement asks the object for an iterator, then calls next() on it once per pass.
- 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.
- 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).
- 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.
- 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.
- 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.
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.
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
What do you think happens?
Suppose keys are added in the order b, a, c. In what order will the key-value tuples appear?
Reveal 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
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.
Reading One Item
Interpret the tuple (apple, 5) as one dictionary item.
- 1First position
The element at index 0 is apple, so apple is the key.
- 2Second position
The element at index 1 is 5, so 5 is the value associated with apple.
- 3Relationship
Together, the tuple represents one complete key-value relationship.
The tuple contains exactly two elements: key apple at index 0 and value 5 at index 1.
Choosing the Right View
| Method | Information emphasized | Useful when |
|---|---|---|
| keys() | Keys alone | You need the identifying parts of the dictionary relationships |
| values() | Values alone | You need the stored results without the keys |
| items() | Each key together with its value | You 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
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?
- 1Record the insertion sequence
The keys were added in the order b, then a, then c.
- 2Keep each relationship together
Each key remains paired with its corresponding value in a two-element tuple.
- 3Apply the ordering rule
The tuple sequence follows insertion order rather than alphabetical order.
The pairs appear in b, a, c order. They are not rearranged into a, b, c order.
Storing and Iterating Pairs
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.
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 likeExpecting apple, mango, zebra merely because that is alphabetical order.
Why it failsThe tuples follow the order in which the keys were added.
Do this insteadTrack 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 likeReading (apple, 5) as one value instead of a pair.
Why it failsEvery item tuple contains both parts of one key-value relationship.
Do this insteadRead 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 likeTrying to replace one element inside a returned tuple.
Why it failsThe tuples returned by
items()are immutable.Do this insteadTreat 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 likeUsing the items result when a function or storage step specifically requires an actual list.
Why it failslist(d.items())is the operation identified for converting thedict_itemsobject into an actual list.Do this insteadUse list(d.items()) when you need a list that can be stored, printed, or passed to a function.
Key Takeaways
- 1
items()is the choice when both keys and values must remain together. - 2The list form contains one two-element tuple for each key-value relationship.
- 3Within each tuple, the key is at index 0 and the value is at index 1.
- 4Tuple order follows dictionary insertion order, not alphabetical order.
- 5Use
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.