Concepts / Dictionary Methods: keys(), values(), and items()

Dictionary Methods: keys(), values(), and items()

Looping through a dictionary directly iterates over its keys, not its values.

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

countsdictionarychuckcurrent keyanniecurrent keyjancurrent keyfirst iterationnext iterationnext iteration
What does each iteration produce when a dictionary is used directly in a for loop?

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.

Code walkthrough
counts = {
    "chuck": 1,
    "annie": 42,
    "jan": 100
}

for key in counts:
    print(key, counts[key])
  1. 1
    The dictionary is created with the keys chuck, annie, and jan.
  2. 2
    On the first iteration, key is chuck, so counts[key] retrieves 1.
  3. 3
    On the second iteration, key is annie, so counts[key] retrieves 42.
  4. 4
    On the third iteration, key is jan, so counts[key] retrieves 100.
  5. 5
    After 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.
Output
chuck 1
annie 42
jan 100
keychuckcounts[key]lookup1associated valuechuck 1printed pairuse as indexretrievesprint keyprint value
How does each key stay connected to its corresponding value while the loop runs?

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

chuckinserted firstchuckvisited firstannieinserted secondannievisited secondjaninserted thirdjanvisited thirdsame positionsame positionsame position
In what order are dictionary keys visited, and how does insertion order determine the loop output?

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?

  • red

  • green

  • blue

Reveal answer
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 expressionWhat the source establishesHow to access the associated value
for key in dictionaryThe loop visits dictionary keysUse dictionary[key]
keys()Named as a dictionary method in this topicThe provided source does not specify additional behavior
values()Named as a dictionary method in this topicThe provided source does not specify additional behavior
items()Named as a dictionary method in this topicThe 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 like
    for value in counts:
        print(value)
    Why it fails

    Direct iteration through a dictionary visits keys, so the variable named value actually receives a key.

    Do this instead

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

    This prints only the current key. It does not retrieve the value associated with that key.

    Do this instead

    Print key together with counts[key] when both parts are needed.

  • Common mistake

    Ignoring insertion order when predicting output

    What it looks like

    Predicting that a later-inserted key will be visited first

    Why it fails

    Dictionary keys maintain insertion order, so the visitation sequence follows the order in which the keys were added.

    Do this instead

    Write down the insertion sequence before tracing the loop.

Best practice

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

Worked example

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?

  1. 1
    Identify the loop input

    The dictionary itself is the sequence used by the for loop, so the loop visits dictionary keys.

  2. 2
    Identify the order

    Dictionary keys maintain insertion order, so the first, second, and third keys are visited in that order.

  3. 3
    Write the output sequence

    The loop variable receives first, then second, then third.

Result

first, second, third

EASY

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

  1. 1
    Using a dictionary directly as the sequence in a for loop visits its keys, not its values.
  2. 2
    The loop variable holds one key at a time.
  3. 3
    Use bracket notation, dictionary[key], to retrieve the value associated with the current key.
  4. 4
    Dictionary keys maintain insertion order, so the visitation sequence is predictable.
  5. 5
    The 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].

Related concepts

More concepts starting with D