Sorting Dictionary Keys
Looping through a dictionary directly iterates over its keys, not its values.
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?
Reveal 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]).
counts = {
"chuck": 1,
"annie": 2,
"jan": 3
}
for key in counts:
print(key, counts[key])- 1On the first iteration, key is chuck, so counts[key] retrieves 1.
- 2On the second iteration, key is annie, so counts[key] retrieves 2.
- 3On the third iteration, key is jan, so counts[key] retrieves 3.
- 4There 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.
chuck 1
annie 2
jan 3Extracting 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.
annie 2
chuck 1
jan 3Tracing 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.
- 1Extract
list(counts.keys())creates a list containing the keys in their stored insertion order: chuck, annie, jan. - 2Sort
keys.sort()rearranges that list alphabetically: annie, chuck, jan. - 3Retrieve
The loop visits annie, chuck, and jan in that sorted sequence. Each key retrieves its value from counts.
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.
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 likefor value in counts:Why it failsDirect iteration through a dictionary visits keys, not values.
Do this insteadUse 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 likecounts.keys().sort()Why it failsThe
keys()method returns adict_keysobject, which does not have asort()method.Do this insteadCreate 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 likekeys = list(counts.keys()) followed by keys.sort()Why it failsThe sort operation changes the separate list, not the original dictionary.
Do this insteadUse 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 likefor key in counts: print(key, counts[key])Why it failsA direct loop follows insertion order, which can differ from alphabetical order.
Do this insteadExtract and sort the keys when alphabetical output is required.
Trace It Yourself
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.
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
- 1A for loop over a dictionary directly visits its keys, not its values.
- 2Dictionary keys are visited in insertion order, so direct-loop output is predictable.
- 3Use dictionary[key] to retrieve the value associated with the current key.
- 4For alphabetical output, extract the keys into a list, sort the list, and loop through it.
- 5Sorting 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.