Concepts / Sorting Dictionary Keys

Sorting Dictionary Keys

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

  • Programming

The Order You See

A dictionary can contain the information you need, but its insertion order may not be the order you want to show. When you loop through a dictionary directly, Python visits its keys in insertion order. If you need alphabetical output, you must create a separate ordered sequence of keys and use that sequence to control the loop.

What do you think happens?

A dictionary receives the keys chuck, annie, and jan in that order. Which key appears first when the dictionary is used directly as the sequence in a for loop?

  • annie

  • chuck

  • jan

Reveal answer
Answer:

chuck

Direct dictionary iteration visits keys in insertion order. The first key inserted is the first key visited.

Direct Dictionary Iteration

When a dictionary is placed after in, the loop variable receives one dictionary key at a time. It does not automatically receive the values. To access the value associated with the current key, use bracket notation: dictionary[key]. The standard pattern is for key in dictionary followed by an expression such as print(key, dictionary[key]).

Code walkthrough
counts = {
    "chuck": 1,
    "annie": 2,
    "jan": 3
}

for key in counts:
    print(key, counts[key])
  1. 1
    On the first iteration, key is chuck, so counts[key] retrieves 1.
  2. 2
    On the second iteration, key is annie, so counts[key] retrieves 2.
  3. 3
    On the third iteration, key is jan, so counts[key] retrieves 3.
  4. 4
    There are no more keys after the third iteration, so the loop ends.
  • The dictionary stores the keys in the insertion sequence chuck, annie, jan.
  • The loop variable key receives chuck, then annie, then jan.
  • counts[key] retrieves the value associated with the current key.
Output
chuck 1
annie 2
jan 3
chuckcurrent key1counts[chuck]anniecurrent key2counts[annie]jancurrent key3counts[jan]lookuplookuplookup
How does each key in the loop connect to and retrieve its corresponding value?

Extracting and Sorting Keys

To produce alphabetical output, use a three-step process. First, call keys() and convert its result to a list with list(dictionary.keys()). Second, call sort() on that list. Third, loop through the sorted list and use each key to retrieve the value from the original dictionary. The key list controls the order, while the dictionary continues to provide the values.

countschuck, annie, jankey listchuck, annie, jansorted keysannie, chuck, jankey-value outputannie, chuck, janlist(counts.keys())sort()loop and look up values
What happens to the keys as they move from the dictionary to a list and then into alphabetical order?
python
Output
annie 2
chuck 1
jan 3
Worked example

Tracing Alphabetical Output

Determine the output order for a dictionary whose keys were inserted as chuck, annie, and jan, then extracted, sorted, and used in a loop.

  1. 1
    Extract

    list(counts.keys()) creates a list containing the keys in their stored insertion order: chuck, annie, jan.

  2. 2
    Sort

    keys.sort() rearranges that list alphabetically: annie, chuck, jan.

  3. 3
    Retrieve

    The loop visits annie, chuck, and jan in that sorted sequence. Each key retrieves its value from counts.

Result

The output order is annie 2, chuck 1, and jan 3.

Preserving the Dictionary

Sorting the extracted list changes the list, not the original dictionary. The dictionary still contains the same key-value associations and retains its insertion order. The sorted list is only a control sequence: it tells the loop which key to request next from the unchanged dictionary.

countschuck, annie, jancountschuck, annie, jankeyschuck, annie, jankeysannie, chuck, janunchangedsort()
Which ordering changes in the sorted list, and which ordering remains unchanged in the original dictionary?
Best practice

Use this pattern when output should be predictable or alphabetically organized, such as a report or user-facing display. The dictionary remains available for lookups, while the separate sorted list determines processing order.

Mistakes in Key Loops

  • Common mistake

    Expecting a direct dictionary loop to produce values automatically.

    What it looks like
    for value in counts:
    Why it fails

    Direct iteration through a dictionary visits keys, not values.

    Do this instead

    Use the loop variable as a key and retrieve the value with counts[key].

  • Common mistake

    Calling sort() directly on the result of keys().

    What it looks like
    counts.keys().sort()
    Why it fails

    The keys() method returns a dict_keys object, which does not have a sort() method.

    Do this instead

    Create a list first with keys = list(counts.keys()), then call keys.sort().

  • Common mistake

    Assuming that sorting the key list sorts the dictionary.

    What it looks like
    keys = list(counts.keys()) followed by keys.sort()
    Why it fails

    The sort operation changes the separate list, not the original dictionary.

    Do this instead

    Use the sorted list to control lookups while treating the dictionary as unchanged.

  • Common mistake

    Predicting alphabetical output from a direct dictionary loop.

    What it looks like
    for key in counts: print(key, counts[key])
    Why it fails

    A direct loop follows insertion order, which can differ from alphabetical order.

    Do this instead

    Extract and sort the keys when alphabetical output is required.

Trace It Yourself

EASY

A dictionary is created with the keys zebra, apple, and mango in that order. Write the key sequence produced by a direct loop. Then write the key sequence produced after extracting the keys into a list and sorting the list.

Hints
  • The direct loop follows insertion order.
  • The sorted loop follows alphabetical order.
  • Separate the key order from the values; this exercise asks only for the keys.
MEDIUM

Given counts = {"zebra": 4, "apple": 7, "mango": 2}, write a loop that prints the key and its value alphabetically by key without changing the dictionary's insertion order.

Hints
  • Create a list with list(counts.keys()).
  • Sort the list with its sort() method.
  • Use counts[key] inside the loop to retrieve each value.

Key Takeaways

  1. 1
    A for loop over a dictionary directly visits its keys, not its values.
  2. 2
    Dictionary keys are visited in insertion order, so direct-loop output is predictable.
  3. 3
    Use dictionary[key] to retrieve the value associated with the current key.
  4. 4
    For alphabetical output, extract the keys into a list, sort the list, and loop through it.
  5. 5
    Sorting the extracted list changes the list's order but does not modify the original dictionary.

At a glance

  • Direct dictionary iteration traverses keys in insertion order.
  • The current key can retrieve its value with bracket notation.
  • Alphabetical output requires extracting keys into a list and sorting that list.
  • The sorted key list controls lookup order while the original dictionary remains unchanged.

Related concepts

More concepts starting with S