List Sorting and the sorted() Function
Sorting dictionaries by value requires reconstructing tuples from (key, value) to (value, key) because Python's tuple sort compares the first element first.
Try it: Sorting with key= and reverse=
How sorted() and list.sort() compute key(item) once per item, order the items by those keys with Python's comparison rules, and keep equal keys in their original order — including py4e's sort-a-dict-by-value pattern.
How it works
- Decorate: call the key function once on every item (no key means the item itself is compared).
- Compare keys with Python's rules: ints by value, strs by code point ('Z' < 'a'), tuples item by item.
- Order the items by key; reverse=True puts the largest key first.
- Stable: items with equal keys keep their original relative order, also with reverse=True.
- sorted() returns a new list; list.sort() rearranges the list in place and returns None; [:N] keeps the first N.
Default run (12 steps): 5 items in their original order. Python will call lambda t: t[1] once per item. … sorted() returned a new list: result = [('fig', 5), ('kiwi', 5), ('pear', 3), ('apple', 3), ('date', 1)].
Simplified: Up to 10 items of one kind (ints, short ASCII words, (word, count) tuples or a small dict) and a fixed menu of key functions. The sorting algorithm itself (Timsort) is not shown — only what it guarantees: the order by key and stability.
Loading the simulation…
Why Tuple Position Matters
A dictionary entry is represented as a (key, value) pair. When these pairs are sorted directly, the key is the first element, so it controls the initial comparison. To sort by value instead, reconstruct every pair as (value, key). The value is then placed first, allowing a simple sorted() call on the reconstructed list to produce value-sorted output.
Reconstructing the Tuple List
The preparation step is a position swap. Start with each dictionary entry in its usual (key, value) form. Build a new list in which the same two pieces of information appear as (value, key). Nothing about the data is discarded; only the tuple positions change. Because the value now occupies the first position, sorted() uses it as the primary sorting criterion.
Preparing Scores for Value-Based Sorting
A dictionary contains the entries red: 8, blue: 3, and green: 5. Construct the value-first tuples needed for sorting by score.
- 1Read the original entries
The entries are represented as (red, 8), (blue, 3), and (green, 5), with each key before its value.
- 2Swap each pair
Reconstruct the entries as (8, red), (3, blue), and (5, green).
- 3Prepare the list
The new list is [(8, red), (3, blue), (5, green)]. Each value is now the first element of its tuple.
The value-first list is [(8, red), (3, blue), (5, green)]. A simple sorted() call can now compare the values first.
Predicting the Sorted Result
What do you think happens?
The value-first tuples are [(8, red), (3, blue), (5, green)]. In what order will sorted() arrange them?
Reveal answer
[(3, blue), (5, green), (8, red)]
Tuple comparison begins with the first element. The first elements are 8, 3, and 5, so the tuples are ordered by those values from smallest to largest.
Tuple sorting is lexicographic: Python compares the first elements first. If the first elements are different, that comparison determines the order. If two first elements are equal, tuple comparison proceeds to the next element. Therefore, in a value-first design, the value is the primary criterion and the key can participate only when the values tie.
Debugging the Original Pairs
The most common mistake is to sort the original (key, value) pairs and expect the values to control the result. The pair still has the key in position one, so tuple comparison begins with the key. Calling .items() by itself does not perform the required position swap. To obtain value-based sorting, manually reconstruct the tuples as (value, key) before calling sorted().
Common mistake Sorting the original (key, value) pairs when the goal is value-based sorting
What it looks likeThe input remains in the form (key, value).
Why it failsThe key is the first tuple element, so tuple comparison uses the key first.
Do this insteadReconstruct each entry as (value, key) before calling sorted().
Common mistake Assuming that .items() alone swaps the sorting criterion
What it looks likeUsing the dictionary's item pairs without rebuilding them.
Why it failsThe pairs are still ordered as (key, value).
Do this insteadUse the item data to create a new list with the value in the first position.
Common mistake Swapping the tuple positions but predicting the result from the keys
What it looks likeExpecting (8, red), (3, blue), and (5, green) to be ordered by red, blue, and green.
Why it failsAfter reconstruction, values are the first elements and therefore the primary comparison.
Do this insteadRead the first element of each reconstructed tuple to predict the sorted order.
Practice and Transfer
A dictionary has the entries oak: 12, pine: 4, and birch: 9. Construct the value-first tuple list, then write the expected order after sorted() compares the tuples.
Hints
- Write each entry first as (key, value).
- Swap the two positions in every tuple.
- Compare the first elements of the reconstructed tuples from smallest to largest.
Checking the Practice Result
Sort the dictionary entries oak: 12, pine: 4, and birch: 9 by value using value-first tuples.
- 1Reconstruct the pairs
The value-first tuples are (12, oak), (4, pine), and (9, birch).
- 2Compare first elements
The first elements are 12, 4, and 9. Their ascending order is 4, 9, and 12.
- 3Reassemble the ordered list
The tuples follow the corresponding keys while keeping the values first.
[(4, pine), (9, birch), (12, oak)]
Key Takeaways
- 1Dictionary entries begin as (key, value) pairs, so the key is compared first when those pairs are sorted directly.
- 2The .items() method alone does not create value-first tuples.
- 3Reconstructing entries as (value, key) places the value in the primary comparison position.
- 4A simple
sorted()call on the reconstructed list produces value-sorted output. - 5Tuple comparison is lexicographic: Python compares the first element first and proceeds to later elements when needed.
At a glance
- Tuple position determines which part of a dictionary entry
sorted()compares first. - Use value-first tuples in the form (value, key) when sorting dictionary data by value.
- Predict the result by reading and ordering the first elements of the reconstructed tuples.
- If sorting gives key-based results, check whether the tuples were actually reconstructed.