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
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])
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.
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.
Extract: list(counts.keys()) creates a list containing the keys in their stored insertion order: chuck, annie, jan.
Sort: keys.sort() rearranges that list alphabetically: annie, chuck, jan.
Retrieve: 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
Expecting a direct dictionary loop to produce values automatically.
Direct iteration through a dictionary visits keys, not values.
Fix:
Use the loop variable as a key and retrieve the value with counts[key].Calling sort() directly on the result of keys().
The keys() method returns a dict_keys object, which does not have a sort() method.
Fix:
Create a list first with keys = list(counts.keys()), then call keys.sort().Assuming that sorting the key list sorts the dictionary.
The sort operation changes the separate list, not the original dictionary.
Fix:
Use the sorted list to control lookups while treating the dictionary as unchanged.Predicting alphabetical output from a direct dictionary loop.
A direct loop follows insertion order, which can differ from alphabetical order.
Fix:
Extract 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
- A for loop over a dictionary directly visits its keys, not its values.
- Dictionary keys are visited in insertion order, so direct-loop output is predictable.
- Use dictionary[key] to retrieve the value associated with the current key.
- For alphabetical output, extract the keys into a list, sort the list, and loop through it.
- Sorting the extracted list changes the list's order but does not modify the original dictionary.
Key Takeaways
- 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.