Unpacking Tuples in For Loops
Sorting dictionaries by value requires reconstructing tuples from (key, value) to (value, key) because Python's tuple sort compares the first element first.
The Sorting Problem
A dictionary item is represented as a tuple in the order (key, value). If you want to sort dictionary data by value, that order is not convenient: tuple sorting examines the first element first. The solution is to unpack each item, then rebuild it as (value, key) before calling sorted().
Tuple Position and Sort Priority
Python's tuple comparison is lexicographic: it gives priority to the first element. Therefore, a tuple shaped like (key, value) is naturally ordered by key, while a tuple shaped like (value, key) is naturally ordered by value. Reconstructing the tuple changes the sort priority without changing the information it contains.
| Tuple shape | First element | Primary sorting basis |
|---|---|---|
| (key, value) | key | key |
| (value, key) | value | value |
The first tuple position determines the primary comparison.
Rebuilding Items in a Loop
The for loop receives each dictionary item as a two-part tuple. Unpacking gives the two parts names such as key and value. The loop then appends a new tuple with those names reversed: (value, key). After every item has been processed, the list contains tuples whose first elements are the values that should control sorting.
scores = {"Ada": 91, "Bo": 75, "Cy": 84} value_key_pairs = [] for key, value in scores.items(): value_key_pairs.append((value, key)) ordered_pairs = sorted(value_key_pairs)
From Reconstruction to Result
Sorting three scores by value
Transform the dictionary items into (value, key) tuples and determine the result of sorted().
Original items: The generated dictionary contains items represented as (key, value): (Ada, 91), (Bo, 75), and (Cy, 84).
Reconstruct each tuple: Unpacking and reversing the positions produces (91, Ada), (75, Bo), and (84, Cy).
Compare position 0: The first elements are 91, 75, and 84. Because value is now first, these numbers determine the primary order.
Apply sorted(): The tuples are ordered from the smallest first element to the largest first element.
[(75, "Bo"), (84, "Cy"), (91, "Ada")]
Ties and Secondary Comparison
The first element remains the primary comparison. If two tuples have the same first element, lexicographic comparison can continue to the next element. For reconstructed tuples, that next element is the key. Thus, when values tie, the keys provide the next comparison position.
What do you think happens?
What order results from sorting [(8, "Zed"), (5, "Mia"), (8, "Ana")]?
Reveal answer
Answer: [(5, "Mia"), (8, "Ana"), (8, "Zed")]
The value is compared first, so 5 comes before 8. The two tuples beginning with 8 tie on their first element, so their second elements are compared next: Ana comes before Zed.
Mistakes in Value Sorting
Sorting the original (key, value) tuples
The key is still in position 0, so tuple sorting uses the key as its primary comparison.
Fix:
Build a list of (value, key) tuples first, then pass that reconstructed list to sorted().Unpacking the item but appending the original order
The loop names the two parts correctly, but the appended tuple leaves the key first.
Fix:
Append (value, key), placing the desired sorting field at position 0.Expecting .items() alone to provide value-sorted results
The .items() method gives key-value tuples, and sorting those tuples prioritizes the key.
Fix:
Manually swap the tuple positions before calling sorted().
Practice the Transformation
Given the dictionary data = {"x": 12, "y": 4, "z": 9}, write the list of reconstructed (value, key) tuples before sorting. Then predict the result of sorted() on that list.
Hints
- Each dictionary item begins in (key, value) order.
- Reverse each pair so the value comes first.
- Compare the first elements from smallest to largest.
Practice solution
Transform {"x": 12, "y": 4, "z": 9} into value-key tuples and sort them.
Unpack the items: The items are (x, 12), (y, 4), and (z, 9).
Reverse each tuple: The reconstructed list is [(12, x), (4, y), (9, z)].
Sort by the first element: The first elements are 12, 4, and 9, so the ascending order is 4, 9, 12.
[(4, "y"), (9, "z"), (12, "x")]
The Working Pattern
- Dictionary items are handled as (key, value) tuples.
- Tuple sorting compares the first element first.
- To sort dictionary data by value, unpack each item and append a (value, key) tuple.
- Calling sorted() on the reconstructed list produces value-based ordering.
- If values tie, tuple comparison can continue to the key in the next position.
Key Takeaways
- Reconstruct dictionary items from (key, value) to (value, key) when value should control sorting.
- Use tuple unpacking in a for loop to access the key and value separately.
- Place the desired primary sorting field at tuple index 0.
- Apply sorted() after building the reconstructed list.
- For equal first elements, lexicographic comparison can use the next tuple element.