Concepts / Iterating Through Dictionary Keys

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.

  • 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…

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.

python
Output
chuck
annie
jan

The 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

countsdictionarykeycurrent keycounts[key]associated valuevalue > 10testselected entrykey and valuegives a keyindexessupplies valuetrue
How does the loop move from each key to its corresponding value so it can test whether the entry should be selected?

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.

Code walkthrough
counts = {
    "chuck": 1,
    "annie": 13,
    "jan": 15
}

for key in counts:
    if counts[key] > 10:
        print(key, counts[key])
  1. 1
    The first key is chuck. counts["chuck"] is 1, so 1 > 10 is false and nothing is printed.
  2. 2
    The next key is annie. counts["annie"] is 13, so 13 > 10 is true and annie 13 is printed.
  3. 3
    The next key is jan. counts["jan"] is 15, so 15 > 10 is true and jan 15 is printed.
  4. 4
    There 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.
Output
annie 13
jan 15

What do you think happens?

Which entries will be printed by the loop, and why?

  • chuck only

  • annie and jan

  • all three entries

  • no entries

Reveal answer
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

anniecurrent keycounts[annie]dictionary lookup13associated valueused as indexretrieves
Why does counts[key] retrieve the value needed for the condition, while the loop variable alone contains only the key?
Definition

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.

ExpressionWhat it representsRole in value filtering
keyThe current dictionary keyIdentifies which entry is being examined
counts[key]The value associated with the current keyProvides the value for the condition
counts[key] > 10A comparison involving that valueDetermines whether the entry is selected

The loop variable supplies the key; bracket notation retrieves the value.

Insertion Order and Output

chuckfirst keyanniesecond keyjanthird keynextnext
In what order does the loop visit the keys, and how does that determine the order of the printed 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.

Worked example

Tracing Both Key and Value

Determine what each iteration holds for the dictionary counts = {"chuck": 1, "annie": 13, "jan": 15}.

  1. 1
    First iteration

    key holds chuck. Looking up counts[key] retrieves 1.

  2. 2
    Second iteration

    key holds annie. Looking up counts[key] retrieves 13.

  3. 3
    Third iteration

    key holds jan. Looking up counts[key] retrieves 15.

  4. 4
    Loop completion

    After jan, there are no more keys, so the loop ends.

Result

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.

python
Output
{'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

OperationWhat the loop doesTypical result
FilteringSelects entries whose values satisfy a conditionA printed selection or a new dictionary containing selected entries
TransformingChanges entries or their representation for a later purposeA 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 like
    if key > 10:
    Why it fails

    The loop variable contains a key. It does not contain the dictionary value that should be tested.

    Do this instead

    Use if counts[key] > 10: so the index operator retrieves the associated value first.

  • Common mistake

    Forgetting the index operator

    What it looks like
    if key == 10:
    Why it fails

    This compares the key directly with 10 rather than testing the value stored under that key.

    Do this instead

    Write the comparison against counts[key].

  • Common mistake

    Using assignment where comparison is intended

    What it looks like
    if counts[key] = 10:
    Why it fails

    The condition needs to compare the retrieved value with a threshold.

    Do this instead
    Use 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 like
    for key in counts: print(key)
    Why it fails

    A direct dictionary loop traverses keys. The value must be retrieved separately.

    Do this instead

    Use print(key, counts[key]) when both the key and its corresponding value are needed.

  • Common mistake

    Modifying the dictionary being traversed

    Why it fails

    Changing the dictionary during iteration is identified as a common mistake in this pattern.

    Do this instead

    Collect selected entries in a new dictionary such as filtered, then use that result afterward.

Practice the Trace

EASY

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.
python
Output
blue 12
green 7

Red 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

  1. 1
    A for loop over a dictionary traverses its keys.
  2. 2
    Use dictionary[key] to retrieve the value associated with the current key.
  3. 3
    To filter by value, test the retrieved value in an if condition.
  4. 4
    Filtered entries can be printed immediately or collected in a new dictionary.
  5. 5
    Dictionary 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.

Related concepts

More concepts starting with I