Concepts / Understanding Dictionary Items and Iteration

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.

  • Programming
Interactive lab

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

  1. Decorate: call the key function once on every item (no key means the item itself is compared).
  2. Compare keys with Python's rules: ints by value, strs by code point ('Z' < 'a'), tuples item by item.
  3. Order the items by key; reverse=True puts the largest key first.
  4. Stable: items with equal keys keep their original relative order, also with reverse=True.
  5. 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.

Educational simulation

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.

("apple", 4)key, value(4, "apple")value, key("pear", 2)key, value(2, "pear")value, keyswap positionsswap positions
How does each dictionary entry change when it is transformed from (key, value) into (value, key), and which element becomes the sorting priority?
python
Output (expected)
[(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.

(3, "Lin")value first3 and 6compare values(3, "Lin") firstsmaller value(6, "Kai")value firstfirst elementsfirst elements3 comes before 6
When Python compares tuples such as (value, key), what does it compare first, and how does that determine the final order?
Worked example

Ordering entries by their values

Given the value-first tuples [(8, "Ada"), (3, "Lin"), (6, "Kai")], predict the result of sorted().

  1. 1
    Compare the first elements

    The first elements are 8, 3, and 6. These are the values, so they determine the primary order.

  2. 2
    Arrange values from smaller to larger

    The value order is 3, then 6, then 8.

  3. 3
    Keep each key with its value

    The key remains the second element of its tuple while the complete tuples are moved into sorted order.

Result

[(3, "Lin"), (6, "Kai"), (8, "Ada")]

0(2, "B")1(4, "A")2(4, "C")next positionsame first value, compare later position
Given several (value, key) tuples, what sequence will sorting produce, especially when two entries have the same value?

Building the Value-First List

dictionarykeys and values.items()(key, value)swap positions(value, key)tuple listready for sorted()read entriesrebuild each tuplecollect tuples
How does data move from the dictionary's key-value items into a new list of (value, key) tuples ready for sorting?
Code walkthrough
prices = {"pen": 4, "book": 9, "cup": 2}
items = prices.items()
value_first = [(value, key) for key, value in items]
result = sorted(value_first)
  1. 1
    The dictionary supplies entries through .items() in (key, value) form.
  2. 2
    The comprehension reads each key and value, then creates a new tuple in (value, key) form.
  3. 3
    The new list places values first, so sorted() compares values first.
  4. 4
    The resulting tuples are ordered from the smallest value to the largest value.
Output
[(2, 'cup'), (4, 'pen'), (9, 'book')]
Best practice

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

(key, value)key controls firstcomparison(value, key)value controls firstcomparisonkey-sorted resultvalue is secondvalue-sorted resultkey is secondsorted()sorted()
What changes when the original (key, value) tuples are sorted directly instead of being reconstructed as (value, key) tuples?
  • Common mistake

    Sorting the original (key, value) tuples and expecting values to control the order.

    What it looks like
    sorted(dictionary.items())
    Why it fails

    The key is the first tuple element, so tuple sorting compares keys first. The value is not in the priority position.

    Do this instead
    Build (value, key) tuples before calling sorted().
  • Common mistake

    Reading the reconstructed tuple as though it were still (key, value).

    What it looks like

    Treating (9, "book") as key 9 and value "book" when it was intentionally built as (value, key).

    Why it fails

    Swapping positions changes the meaning of each position.

    Do this instead

    Keep 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 like

    Sorting the key-first list and only then exchanging the elements.

    Why it fails

    The sort has already used the key as its first comparison element.

    Do this instead

    Reconstruct 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")]?

  • [(2, "blue"), (5, "amber"), (5, "red")]

  • [(5, "red"), (5, "amber"), (2, "blue")]

  • [(5, "amber"), (2, "blue"), (5, "red")]

Reveal answer
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".

MEDIUM

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

  1. 1
    Dictionary items begin in (key, value) form.
  2. 2
    Python's tuple sorting compares the first element first.
  3. 3
    To sort dictionary entries by value, reconstruct them as (value, key).
  4. 4
    After reconstruction, sorted() can order the tuples by their values.
  5. 5
    When 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.

Related concepts

More concepts starting with U