Sorting Lists with .sort() and sorted()
Sorting the tuple pairs does not separate the keys from their values. The pair (apple, 2) remains one tuple after sorting; only its position in the list changes.
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…
From Dictionary to Sortable Data
A dictionary contains key-value pairs, but the sorting operation in this lesson is performed on a list. The bridge between these two structures is list(d.items()). It takes the dictionary's items and represents them as a list of tuples, so the pairs can be sorted as list elements.
Preparing Dictionary Contents
Suppose d contains the key-value pairs pear: 4, apple: 2, and orange: 3. What structure does list(d.items()) create?
- 1Start with the dictionary
The data is held as key-value pairs.
- 2Read the items
d.items()provides the dictionary items for conversion. - 3Create the list
list(d.items())represents each key-value pair as a tuple inside a list.
The resulting list contains the tuples (pear, 4), (apple, 2), and (orange, 3), with each key at position 0 and each value at position 1.
Why Tuple Position Matters
Each tuple produced from a dictionary item has two positions. The key is at index 0, and the value is at index 1. When .sort() is called on the list of tuples, Python sorts by the first element by default. Because the first element is the key, the default result is an ascending alphabetical order of keys.
| Tuple position | Contents | Role in the default sort |
|---|---|---|
| Index 0 | Dictionary key | Compared first |
| Index 1 | Dictionary value | Not used first when sorting by default |
The tuple layout explains why dictionary contents sort by key.
Alphabetical Key Order
Consider a list containing the generated tuple pairs (pear, 4), (apple, 2), and (orange, 3). The keys are pear, apple, and orange. Since .sort() examines the first element of each tuple, the pairs move into the order apple, orange, pear. The values stay attached to their original keys because each key and value remains inside the same tuple.
Sorting the tuple pairs does not separate the keys from their values. The pair (apple, 2) remains one tuple after sorting; only its position in the list changes.
Choosing .sort() or sorted()
| Operation | What it works with | Result |
|---|---|---|
| .sort() | The list of tuples | Sorts that list |
| sorted() | The data being sorted | Provides a separately sorted list |
Both names describe sorting, but the operations are distinguished by whether the existing list is sorted or a separate sorted list is obtained.
The Dictionary Stays Unchanged
list(d.items()) creates a list representation of the dictionary's items. Sorting that list changes the order of the tuple elements in the list, not the dictionary itself. The original dictionary remains separate from the sorted list.
When checking whether a sort changed your data, identify which object you passed to the sorting operation. If it was the list created from d.items(), inspect that list separately from the original dictionary.
Mistakes to Avoid
Common mistake Trying to sort the dictionary contents without first converting the items to a list of tuples.
What it looks likeTreating d itself as though it were already the list being sorted.
Why it failsThe described sorting process uses
list(d.items())to create the sortable list.Do this insteadConvert the items with list(d.items()), then sort the resulting list.
Common mistake Assuming the value controls the default order.
What it looks likeExpecting a pair with a smaller value to appear first even when its key comes later alphabetically.
Why it failsEach tuple stores the key at index 0, and .sort() compares the first tuple element by default.
Do this insteadLook at the keys first when predicting the default order.
Common mistake Expecting the original dictionary to be reordered by sorting the tuple list.
What it looks likeSorting the list from d.items() and then assuming d itself was modified.
Why it failsThe sorted list is separate from the original dictionary.
Do this insteadTreat the sorted tuple list and the dictionary as separate objects.
A dictionary has the generated items banana: 5, apple: 8, and cherry: 2. Describe the list of tuples produced by list(d.items()), then state the alphabetical order of the tuple keys after the list is sorted by default. Finally, explain whether the original dictionary is modified.
Hints
- Each dictionary item becomes one tuple.
- The key is at tuple index 0.
- The original dictionary and the sorted tuple list are separate.
Key Takeaways
- 1Use
list(d.items())to represent dictionary contents as a list of key-value tuples. - 2Each tuple places the key at index 0 and the value at index 1.
- 3The default .sort() order uses the first tuple element, so tuple pairs are ordered by key alphabetically.
- 4The list of tuples is separate from the original dictionary, so sorting the list does not modify the dictionary.
- 5.sort() sorts the existing list, while
sorted()provides a separately sorted list.
At a glance
- Convert dictionary items with
list(d.items())before sorting them as a list. - A tuple stores its key first and its value second.
- Default sorting of the tuple list compares keys in ascending alphabetical order.
- Sorting the tuple list does not modify the original dictionary.
- .sort() operates on an existing list, whereas
sorted()provides a separate sorted list.