Understanding Dictionary Items and Iteration
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…
The Sorting Problem
A dictionary entry is represented as a pair containing a key and a value. When dictionary items are used directly, their tuple shape is (key, value). If the goal is to sort by value, that arrangement puts the value in the wrong position for Python's tuple sorting rule. The solution is to reconstruct each pair as (value, key), placing the desired sorting information first.
Reconstructing Each Entry
The .items() method supplies dictionary entries in the form (key, value). That form is useful for accessing both parts of an entry, but it does not make the value the first comparison element. To prepare for value-based sorting, take each item and swap its positions. The resulting tuple has the form (value, key). After every entry has been transformed, the collection is ready for a simple sorted() call.
[(3, 'Lin'), (6, 'Kai'), (8, 'Ada')]How Tuple Sorting Chooses Order
Python's tuple sorting is lexicographic: tuple positions are considered from left to right. For value-first tuples, the first element is the value, so values determine the main order. If two tuples have the same first element, the later element is used to distinguish them. Because the key is second in a (value, key) tuple, the key can determine the order between entries that share a value.
Ordering entries by their values
Given the value-first tuples [(8, "Ada"), (3, "Lin"), (6, "Kai")], predict the result of sorted().
- 1Compare the first elements
The first elements are 8, 3, and 6. These are the values, so they determine the primary order.
- 2Arrange values from smaller to larger
The value order is 3, then 6, then 8.
- 3Keep each key with its value
The key remains the second element of its tuple while the complete tuples are moved into sorted order.
[(3, "Lin"), (6, "Kai"), (8, "Ada")]
Building the Value-First List
prices = {"pen": 4, "book": 9, "cup": 2}
items = prices.items()
value_first = [(value, key) for key, value in items]
result = sorted(value_first)- 1The dictionary supplies entries through .items() in (key, value) form.
- 2The comprehension reads each key and value, then creates a new tuple in (value, key) form.
- 3The new list places values first, so
sorted()compares values first. - 4The resulting tuples are ordered from the smallest value to the largest value.
[(2, 'cup'), (4, 'pen'), (9, 'book')]Separate the transformation from the sorting step while learning or debugging. First inspect the value-first list. Once its tuple shape is correct, apply sorted(). This makes it easier to see whether the problem is in reconstruction or in the expected ordering.
Mistakes with Tuple Position
Common mistake Sorting the original (key, value) tuples and expecting values to control the order.
What it looks likesorted(dictionary.items())Why it failsThe key is the first tuple element, so tuple sorting compares keys first. The value is not in the priority position.
Do this insteadBuild (value, key) tuples before calling sorted().Common mistake Reading the reconstructed tuple as though it were still (key, value).
What it looks likeTreating (9, "book") as key 9 and value "book" when it was intentionally built as (value, key).
Why it failsSwapping positions changes the meaning of each position.
Do this insteadKeep the labels value first and key second throughout the sorting step.
Common mistake Swapping the tuple positions after sorting instead of before sorting.
What it looks likeSorting the key-first list and only then exchanging the elements.
Why it failsThe sort has already used the key as its first comparison element.
Do this insteadReconstruct every tuple as (value, key) before applying sorted().
Practice the Transformation
What do you think happens?
What will sorted() produce from [(5, "red"), (2, "blue"), (5, "amber")]?
Reveal answer
[(2, "blue"), (5, "amber"), (5, "red")]
The values are compared first, so 2 comes before 5. The two tuples with value 5 are then distinguished by their second elements, "amber" and "red".
A dictionary contains {"oak": 7, "elm": 3, "pine": 7}. Write the value-first tuple list that should be passed to sorted(), then predict the resulting order.
Hints
- Read each entry as (key, value) first.
- Rebuild each entry as (value, key).
- Compare the values first, and use the keys to distinguish the two entries whose value is 7.
Key Takeaways
- 1Dictionary items begin in (key, value) form.
- 2Python's tuple sorting compares the first element first.
- 3To sort dictionary entries by value, reconstruct them as (value, key).
- 4After reconstruction,
sorted()can order the tuples by their values. - 5When values match, the later tuple element can determine the order.
At a glance
- Use (value, key) rather than (key, value) when value should control tuple sorting.
- Construct the value-first list before calling
sorted(). - Tuple position determines which part of each dictionary entry receives sorting priority.
- If two values match, the later tuple element can distinguish the entries.