Dictionary Methods: keys(), values(), and items()
Looping through a dictionary directly iterates over its keys, not its values.
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…
The First Iteration
A dictionary contains key-value associations, so it is natural to wonder what a for loop produces when the dictionary itself appears after in. The important behavior is that direct iteration through a dictionary visits its keys, not its values. The loop variable receives one key at a time.
Tracing the Current Key
During each iteration, the loop variable holds the current key. The value is not placed into the loop variable automatically. To obtain it, use bracket notation with the current key: dictionary[key]. This creates a two-step trace: identify the key currently held by the loop variable, then use that key to retrieve its associated value.
counts = {
"chuck": 1,
"annie": 42,
"jan": 100
}
for key in counts:
print(key, counts[key])- 1The dictionary is created with the keys chuck, annie, and jan.
- 2On the first iteration, key is chuck, so counts[key] retrieves 1.
- 3On the second iteration, key is annie, so counts[key] retrieves 42.
- 4On the third iteration, key is jan, so counts[key] retrieves 100.
- 5After the third key has been processed, there are no more keys and the loop ends.
- The dictionary is used directly as the sequence in the loop.
- The variable key receives one dictionary key at a time.
- counts[key] retrieves the value associated with the current key.
- The print statement displays the key and its retrieved value together.
chuck 1
annie 42
jan 100Insertion Order
Dictionary keys maintain insertion order. Therefore, when keys are added in a particular order and the dictionary is later traversed, the loop visits those keys in that same order. This makes the loop's behavior predictable: to predict the output, first identify the order in which the keys were inserted, then trace the value lookup for each key.
What do you think happens?
A dictionary has keys inserted in this order: red, green, blue. What key will the loop variable receive first when the dictionary is traversed?
Reveal answer
red
Dictionary keys maintain insertion order, so the first inserted key is visited first.
Methods and Iteration Choices
The topic includes keys(), values(), and items(), but the central iteration rule established here is about using the dictionary directly: direct iteration produces keys. Once the loop variable contains a key, bracket notation retrieves the corresponding value. The standard pattern for accessing both parts is for key in dict followed by dict[key].
| Loop expression | What the source establishes | How to access the associated value |
|---|---|---|
| for key in dictionary | The loop visits dictionary keys | Use dictionary[key] |
| keys() | Named as a dictionary method in this topic | The provided source does not specify additional behavior |
| values() | Named as a dictionary method in this topic | The provided source does not specify additional behavior |
| items() | Named as a dictionary method in this topic | The provided source does not specify additional behavior |
The key behavior taught in this article is direct dictionary iteration and bracket lookup.
Mistakes Beginners Make
Common mistake Expecting direct dictionary iteration to produce values
What it looks likefor value in counts: print(value)Why it failsDirect iteration through a dictionary visits keys, so the variable named value actually receives a key.
Do this insteadUse a key-oriented variable name, such as key, and retrieve the value with counts[key].
Common mistake Printing the key without looking up its value
What it looks likefor key in counts: print(key)Why it failsThis prints only the current key. It does not retrieve the value associated with that key.
Do this insteadPrint key together with counts[key] when both parts are needed.
Common mistake Ignoring insertion order when predicting output
What it looks likePredicting that a later-inserted key will be visited first
Why it failsDictionary keys maintain insertion order, so the visitation sequence follows the order in which the keys were added.
Do this insteadWrite down the insertion sequence before tracing the loop.
When debugging a dictionary loop, make a small trace table with one row per iteration. Record the current key first, then evaluate dictionary[key] to find the associated value. This makes the order and the lookup step visible instead of leaving them implicit.
Practice the Trace
Predicting a key loop
Suppose a dictionary has keys inserted in the order first, second, third. A loop uses the dictionary directly and prints its loop variable. What sequence of values should be predicted?
- 1Identify the loop input
The dictionary itself is the sequence used by the for loop, so the loop visits dictionary keys.
- 2Identify the order
Dictionary keys maintain insertion order, so the first, second, and third keys are visited in that order.
- 3Write the output sequence
The loop variable receives first, then second, then third.
first, second, third
A dictionary contains the keys alpha, beta, and gamma in that insertion order. Describe the value of the loop variable on each iteration. Then explain how you would retrieve the value associated with the current key.
Hints
- Direct dictionary iteration visits keys.
- Use the insertion order to determine the sequence.
- The associated value is retrieved with dictionary[key].
Key Takeaways
- 1Using a dictionary directly as the sequence in a for loop visits its keys, not its values.
- 2The loop variable holds one key at a time.
- 3Use bracket notation, dictionary[key], to retrieve the value associated with the current key.
- 4Dictionary keys maintain insertion order, so the visitation sequence is predictable.
- 5The standard pattern for accessing both parts is for key in dict followed by dict[key].
At a glance
- A direct for loop over a dictionary iterates through keys.
- The current key can be used with bracket notation to retrieve its associated value.
- Dictionary keys are visited in insertion order.
- To predict a loop's output, trace the inserted keys from first to last.
- The standard key-and-value pattern is for key in dict followed by dict[key].