Sorting Lists in Python
The sorted list controls the order of access. The original dictionary remains available to provide the values.
Why Output Order Matters
A dictionary can contain the information you need while still presenting that information in an order you do not want. If you need an alphabetical report, consistent user-facing output, or predictable processing order, use a separate list of keys to control the sequence. The essential pattern is extract, sort, and iterate.
The sorted list controls the order of access. The original dictionary remains available to provide the values.
Extracting Keys into a List
Begin with the dictionary's keys() method. The expression dict.keys() returns a dict_keys object, so convert it with list() before trying to sort it. The resulting list contains the dictionary's keys in the order in which they were stored at that point. That order is not necessarily alphabetical.
Reordering the Key List
What do you think happens?
After these statements run, what happens to the list and to the dictionary?
keys = list(counts.keys())
keys.sort()Reveal answer
Only the list is reordered.
The sort() method rearranges the list in place. The dictionary is not changed; it remains the source used for later value lookups.
Looking Up Values in Order
Once the key list is sorted, use a for loop to visit each key. For every key, counts[key] looks in the original dictionary and retrieves the associated value. The loop therefore produces key-value output in the order established by the sorted list, while the dictionary itself is only being queried.
counts = {"pear": 4, "apple": 7, "orange": 2}
keys = list(counts.keys())
keys.sort()
for key in keys:
print(key, counts[key])- 1The dictionary contains the key-value pairs.
- 2The separate keys list becomes the sequence that controls output.
- 3
sort()changes the order of the keys list, not the dictionary. - 4The loop begins with the alphabetically first key and continues through the list.
- 5counts[key] retrieves the value associated with the current key.
- Create the dictionary that supplies the values.
- Extract the dictionary keys into a list.
- Rearrange the list alphabetically in place.
- Visit each key in the sorted list.
- Use the current key to retrieve its value from counts.
apple 7
orange 2
pear 4Keeping the Dictionary Untouched
| Object | Role | Changed by keys.sort()? |
|---|---|---|
| keys | Controls the order in which the loop visits entries | Yes |
| counts | Provides the values during each lookup | No |
The extracted list and the original dictionary have different roles in the process.
Treat the sorted list as a control sequence rather than as a replacement for the dictionary. The list determines when each key is used; the dictionary remains the place from which the associated value is retrieved.
Mistakes to Avoid
Common mistake Calling sort() directly on dict.keys().
What it looks likecounts.keys().sort()Why it failskeys()returns adict_keysobject, anddict_keysobjects do not have asort()method.Do this insteadConvert the keys first: keys = list(counts.keys()), then call keys.sort().
Common mistake Expecting keys.sort() to reorder the dictionary.
What it looks likekeys = list(counts.keys()) keys.sort()Why it failssort()changes the separate list in place. The original dictionary remains unchanged.Do this insteadUse the sorted list in the loop when you need alphabetical output.
Common mistake Sorting the keys but not iterating through the sorted list.
What it looks likekeys = list(counts.keys()) keys.sort() for key in counts: print(key, counts[key])Why it failsThe loop must use the sorted list for the sorted sequence to control output order.
Do this insteadIterate with for key in keys: and use counts[key] for the lookup.
Practice the Three Steps
Write the three-step pattern for a dictionary named prices. Your solution should extract its keys into a list, sort that list alphabetically, and loop through the sorted keys to display each key with prices[key].
Hints
- Start with
list(prices.keys()). - Call
sort()on the resulting list. - Use the sorted list as the sequence in the for loop.
Check your solution in order: extract the keys, sort the list, then use each sorted key to look up a value in the original dictionary.
Key Takeaways
- Use
list(dict.keys())to turn the dictionary keys into a sortable list. - Call
sort()on that list to arrange the keys alphabetically in place. - Iterate through the sorted list to control the order of output.
- Use dictionary[key] during each iteration to retrieve the associated value.
- Sorting the extracted list does not modify the original dictionary.