Concepts / List Sorting and the sorted() Function

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.

  • 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…

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.

(key, value)key compared firstkeyfirst elementvaluefirst elementvaluesecond element(value, key)value compared firstkeysecond elementposition 1position 2position 1position 2
How does changing each tuple from (key, value) to (value, key) change which data Python compares first?

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.

(red, 8)dictionary entry(8, red)value first(blue, 3)dictionary entry(3, blue)value first(green, 5)dictionary entry(5, green)value firstswap positionsswap positionsswap positions
How does each dictionary entry move from a (key, value) pair into a new list whose first element is the value?
Worked example

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.

  1. 1
    Read the original entries

    The entries are represented as (red, 8), (blue, 3), and (green, 5), with each key before its value.

  2. 2
    Swap each pair

    Reconstruct the entries as (8, red), (3, blue), and (5, green).

  3. 3
    Prepare the list

    The new list is [(8, red), (3, blue), (5, green)]. Each value is now the first element of its tuple.

Result

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?

  • [(3, blue), (5, green), (8, red)]

  • [(8, red), (5, green), (3, blue)]

  • [(blue, 3), (green, 5), (red, 8)]

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

(3, blue)first value: 3(5, green)first value: 5(8, red)first value: 83 before 55 before 8
In what order will the reconstructed tuples appear after sorted() compares their first elements?

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.

Two tuplesCompare firstelementsFirst elements differTuple orderCompare next elementsbegindifferentequaldecidedecide
What happens when two tuples have the same first element, and which element does Python compare next?

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().

(key, value)key first(value, key)value firstsorted comparessorted compares
What is wrong when sorting the original (key, value) tuples, and how does the corrected tuple construction fix the result?
  • Common mistake

    Sorting the original (key, value) pairs when the goal is value-based sorting

    What it looks like

    The input remains in the form (key, value).

    Why it fails

    The key is the first tuple element, so tuple comparison uses the key first.

    Do this instead

    Reconstruct each entry as (value, key) before calling sorted().

  • Common mistake

    Assuming that .items() alone swaps the sorting criterion

    What it looks like

    Using the dictionary's item pairs without rebuilding them.

    Why it fails

    The pairs are still ordered as (key, value).

    Do this instead

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

    Expecting (8, red), (3, blue), and (5, green) to be ordered by red, blue, and green.

    Why it fails

    After reconstruction, values are the first elements and therefore the primary comparison.

    Do this instead

    Read the first element of each reconstructed tuple to predict the sorted order.

Practice and Transfer

MEDIUM

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.
Worked example

Checking the Practice Result

Sort the dictionary entries oak: 12, pine: 4, and birch: 9 by value using value-first tuples.

  1. 1
    Reconstruct the pairs

    The value-first tuples are (12, oak), (4, pine), and (9, birch).

  2. 2
    Compare first elements

    The first elements are 12, 4, and 9. Their ascending order is 4, 9, and 12.

  3. 3
    Reassemble the ordered list

    The tuples follow the corresponding keys while keeping the values first.

Result

[(4, pine), (9, birch), (12, oak)]

Key Takeaways

  1. 1
    Dictionary entries begin as (key, value) pairs, so the key is compared first when those pairs are sorted directly.
  2. 2
    The .items() method alone does not create value-first tuples.
  3. 3
    Reconstructing entries as (value, key) places the value in the primary comparison position.
  4. 4
    A simple sorted() call on the reconstructed list produces value-sorted output.
  5. 5
    Tuple 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.

Related concepts

More concepts starting with L