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

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

gives a keyindexessupplies valuetruecountsdictionarykeycurrent keycounts[key]associated valuevalue > 10testselected entrykey and value
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.

counts = { "chuck": 1, "annie": 13, "jan": 15 } for key in counts: if counts[key] > 10: print(key, counts[key])

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

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

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

Insertion Order and Output

nextnextchuckfirst keyanniesecond keyjanthird key
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.

Tracing Both Key and Value

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

First iteration: key holds chuck. Looking up counts[key] retrieves 1.

Second iteration: key holds annie. Looking up counts[key] retrieves 13.

Third iteration: key holds jan. Looking up counts[key] retrieves 15.

Loop 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.

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

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

  • Comparing the key instead of the value

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

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

  • Forgetting the index operator

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

    Fix: Write the comparison against counts[key].

  • Using assignment where comparison is intended

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

    Fix: Use a comparison such as counts[key] == 10 or counts[key] > 10.

  • Expecting the loop variable to contain both pieces of the entry

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

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

  • Modifying the dictionary being traversed

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

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

Key Takeaways

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