Iterating Through Dictionary Keys
A for loop over a dictionary iterates through keys; to filter by value, use the index operator to retrieve each value and test it against a condition.
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 Key-First Loop
When a dictionary is used directly as the sequence in a for loop, Python gives the loop one key at a time. It does not automatically give the loop the corresponding values. This key-first behavior is the foundation for both ordinary dictionary traversal and filtering dictionary entries by value.
chuck
annie
janThe loop variable key contains the current key, such as chuck or annie. To obtain the associated count, use the current key inside bracket notation: counts[key]. The loop therefore has two separate actions: it receives a key from the dictionary, then uses that key to retrieve the value.
Following a Value Filter
Filtering by value combines three elements. First, the for statement supplies a key. Second, the index operator retrieves the value associated with that key. Third, an if statement tests the retrieved value. Only when the condition is true does the loop body run for that entry.
counts = {
"chuck": 1,
"annie": 13,
"jan": 15
}
for key in counts:
if counts[key] > 10:
print(key, counts[key])- 1The first key is chuck. counts["chuck"] is 1, so 1 > 10 is false and nothing is printed.
- 2The next key is annie. counts["annie"] is 13, so 13 > 10 is true and annie 13 is printed.
- 3The next key is jan. counts["jan"] is 15, so 15 > 10 is true and jan 15 is printed.
- 4There are no more keys, so the loop ends.
- counts supplies the dictionary being traversed.
- key holds one dictionary key at a time.
- counts[key] retrieves the value for the current key.
- The condition keeps only values greater than 10.
- The print statement runs only for entries that pass the condition.
annie 13
jan 15What do you think happens?
Which entries will be printed by the loop, and why?
Reveal answer
annie and jan
Their values are 13 and 15, which are both greater than 10. Chuck has a value of 1, so that entry does not satisfy the condition.
The Bracket Lookup
The index operator is the bracket notation used to retrieve a dictionary value from a key. During iteration, counts[key] means: use the current key to look up its associated value in counts.
The expression key and the expression counts[key] are not interchangeable. key refers to the dictionary key currently held by the loop variable. counts[key] refers to the value stored under that key. A condition that is meant to test counts must therefore compare counts[key], not key.
| Expression | What it represents | Role in value filtering |
|---|---|---|
| key | The current dictionary key | Identifies which entry is being examined |
| counts[key] | The value associated with the current key | Provides the value for the condition |
| counts[key] > 10 | A comparison involving that value | Determines whether the entry is selected |
The loop variable supplies the key; bracket notation retrieves the value.
Insertion Order and Output
Dictionary keys maintain insertion order. If the dictionary is created with chuck first, annie second, and jan third, a direct for loop visits those keys in that same order. This makes the order of printed output predictable and makes it possible to trace the loop one iteration at a time.
Tracing Both Key and Value
Determine what each iteration holds for the dictionary counts = {"chuck": 1, "annie": 13, "jan": 15}.
- 1First iteration
key holds chuck. Looking up counts[key] retrieves 1.
- 2Second iteration
key holds annie. Looking up counts[key] retrieves 13.
- 3Third iteration
key holds jan. Looking up counts[key] retrieves 15.
- 4Loop completion
After jan, there are no more keys, so the loop ends.
The loop visits chuck, then annie, then jan. A statement that prints both key and counts[key] prints the corresponding key-value pairs in that order.
Keeping the Selected Entries
Printing a passing entry is useful when inspecting a loop. When the selected entries are needed later, assign each passing key-value pair to a new dictionary. The original dictionary is used for the iteration, while filtered stores only the entries that satisfy the condition.
{'annie': 13, 'jan': 15}This is filtering: the loop selects existing entries whose values pass the test. The selected key and its existing value are placed in filtered. The loop does not change those entries while selecting them. A filtered dictionary can later be passed to other functions, iterated again, or modified further.
A list can also be used when the later task needs only the selected keys or another collected representation. The essential filtering step remains the same: iterate through keys, retrieve each value with bracket notation, and keep the entry when the condition is true.
Filtering Versus Changing
| Operation | What the loop does | Typical result |
|---|---|---|
| Filtering | Selects entries whose values satisfy a condition | A printed selection or a new dictionary containing selected entries |
| Transforming | Changes entries or their representation for a later purpose | A modified or differently represented result |
Filtering answers which entries should remain; transforming concerns changing entries after or as part of another operation.
For the pattern in this article, the condition selects entries based on their values. Assigning filtered[key] = counts[key] preserves the selected key and value in a new dictionary. That is different from selecting an entry and then modifying it. Keeping this distinction clear helps you identify whether your loop is choosing existing data or producing changed data.
Mistakes That Break the Filter
Common mistake Comparing the key instead of the value
What it looks likeif key > 10:Why it failsThe loop variable contains a key. It does not contain the dictionary value that should be tested.
Do this insteadUse if counts[key] > 10: so the index operator retrieves the associated value first.
Common mistake Forgetting the index operator
What it looks likeif key == 10:Why it failsThis compares the key directly with 10 rather than testing the value stored under that key.
Do this insteadWrite the comparison against counts[key].
Common mistake Using assignment where comparison is intended
What it looks likeif counts[key] = 10:Why it failsThe condition needs to compare the retrieved value with a threshold.
Do this insteadUse a comparison such as counts[key] == 10 or counts[key] > 10.Common mistake Expecting the loop variable to contain both pieces of the entry
What it looks likefor key in counts: print(key)Why it failsA direct dictionary loop traverses keys. The value must be retrieved separately.
Do this insteadUse print(key, counts[key]) when both the key and its corresponding value are needed.
Common mistake Modifying the dictionary being traversed
Why it failsChanging the dictionary during iteration is identified as a common mistake in this pattern.
Do this insteadCollect selected entries in a new dictionary such as filtered, then use that result afterward.
Practice the Trace
Given the dictionary scores = {"red": 4, "blue": 12, "green": 7}, write a for loop that prints the keys and values whose values are greater than 5. Before checking your result, predict the order of the output.
Hints
- A direct loop over scores supplies one key at a time.
- Use scores[key] to retrieve the value for the current key.
- The dictionary was created in the order red, blue, green.
blue 12
green 7Red is examined first but is not printed because its value is 4. Blue is printed next because 12 is greater than 5. Green is printed last because 7 is also greater than 5. The output order follows the dictionary's insertion order, while the condition determines which entries appear.
Key Takeaways
- 1A for loop over a dictionary traverses its keys.
- 2Use dictionary[key] to retrieve the value associated with the current key.
- 3To filter by value, test the retrieved value in an if condition.
- 4Filtered entries can be printed immediately or collected in a new dictionary.
- 5Dictionary keys maintain insertion order, so the loop and its output follow that order.
At a glance
- A dictionary used directly in a for loop supplies keys, not values.
- The current key must be used with bracket notation to retrieve its value.
- Filtering selects entries whose values satisfy a condition; it does not by itself transform them.
- Selected entries can be printed or collected into a new dictionary.
- Keys are visited in insertion order, which makes loop output predictable.