Home / Blog / Programming / Python
How to Sort a Dictionary in Python
Programming · Python · 6 min read
Sort a Python dictionary by key or by value, in either direction, with a new dictionary that keeps the sorted order.
The one line that sorts a dictionary
A dictionary is a collection of key-value pairs. Each key is a label, and each value is the data stored under that label. A dictionary keeps its pairs in the order they were added, but that order is not sorted order.
Sorting a dictionary means making a new dictionary whose pairs sit in a chosen order. The original dictionary does not move. The built-in function sorted takes a collection and returns its items in order, as a list.
The method items gives back the pairs of a dictionary, one pair at a time. Each pair is a small two-part value holding a key and its value. Wrapping the sorted pairs in dict turns them back into a dictionary. That is the whole pattern, and every example below is a change to what sorted compares.
scores = {"maya": 82, "leo": 95, "ana": 82, "tom": 71}
by_key = dict(sorted(scores.items()))
print(by_key)Sort by key
Sorting by key is the default. When sorted receives pairs with no extra instruction, it compares the first part of each pair. The first part is the key, so the pairs come out in key order.
For words, key order is alphabetical order, with one surprise covered below. For numbers, key order is numeric order. Small numbers come first, and larger numbers come later, even when the numbers were added in a different order.
Sorting by key is the right choice when the labels matter most. A word list, a set of city names, or a table of contents all read better in key order. The values simply travel with their keys, unchanged.
One point deserves care. Adding a new pair later puts it at the end of the new dictionary, not in sorted position. A sorted dictionary is a snapshot of one moment, not a container that stays sorted on its own.
stock = {"plums": 12, "apples": 40, "pears": 9}
by_name = dict(sorted(stock.items()))
print(by_name)Sort by value
Sorting by value needs one extra instruction. The sorted function accepts a key argument, and that word key means something different here. It is a small function that tells sorted what to compare for each pair.
A lambda is a small function written in one line, without a name. The lambda in the example takes one pair and returns its second part. The second part is the value, so sorted now compares values instead of keys.
This is the right choice for rankings. Test scores, prices, vote counts, and rainfall totals all make sense in value order. The labels still travel with their values, so the highest score stays attached to the person who earned it.
Values that are compared must be of kinds that can be compared with each other. Numbers compare with numbers, and words compare with words. Mixing numbers and words in one sort raises an error, because Python has no sensible order for that mix.
scores = {"maya": 82, "leo": 95, "ana": 82, "tom": 71}
by_score = dict(sorted(scores.items(), key=lambda pair: pair[1]))
print(by_score)Reverse the order, and take only the top few
Descending order means largest first. Add reverse=True to sorted, and the same sort runs in the opposite direction. Nothing else in the pattern changes, and the original dictionary still stays untouched.
Descending value order is the natural shape for a leaderboard. The top score appears first, and the rest follow in falling order. Descending key order is less common, but it works the same way for any sort.
Sometimes only the first few pairs are needed. In that case, keep the sorted pairs as a list and take a slice of it. A slice is a short section cut from a list, written with a colon and a count. Taking the first two pairs gives the top two, without building a whole new dictionary first.
This matters when the dictionary is large and only a short ranking is shown. Sorting the full set is still needed to know which pairs are on top. The saving comes from not rebuilding and storing a full dictionary that will never be read in full.
scores = {"maya": 82, "leo": 95, "ana": 82, "tom": 71}
ranked = sorted(scores.items(), key=lambda pair: pair[1], reverse=True)
print(ranked[:2])Break ties, and sort by a field inside the value
Equal values are common. Two people can share a score, and two towns can share a rainfall total. Python handles this calmly, because its sort is stable. Stable means pairs that compare equal keep the relative order they had before sorting.
Stability is often enough, but it is not always the clearest result. The order of tied pairs then depends on the order they were added, which a reader cannot see. A second sort field removes that guesswork.
A second field is added by returning a pair of values from the lambda, instead of one value. Python compares the first value first, and only looks at the second value when the first values are equal. Sorting by score and then by name gives every tied pair a fixed, readable place.
The same idea reaches inside a value. When each value is itself a small dictionary, the lambda can return one field from inside it, such as a points total. The outer pairs are then sorted by that inner field, while the full inner data stays intact.
scores = {"maya": 82, "leo": 95, "ana": 82, "tom": 71}
ordered = dict(sorted(scores.items(), key=lambda pair: (pair[1], pair[0])))
print(ordered)Handle capitals, and know what sorting cannot do
Capitals cause the most common surprise. Plain sorting places every uppercase letter before every lowercase letter, because it compares letters by their code values. A word starting with a capital letter therefore sorts before a word starting with a lowercase letter, even when the lowercase word comes earlier in the alphabet.
The fix is to compare a folded form of the key. The casefold method returns a version of a word with capitals lowered, for comparison only. The original keys stay exactly as written, with their capitals intact, while the order follows the alphabet as a reader expects.
Two limits are worth knowing plainly. A dictionary has no sort method of its own, so writing scores.sort() fails. Sorting also cannot repair a dictionary whose values cannot be compared, and it cannot keep a dictionary sorted after new pairs are added.
The working habit is simple. Sort when a readable order is needed, keep the sorted result under a clear name, and sort again when the data changes. Sorting is a view of the data at one moment, and a fresh sort is cheap and clear whenever that moment passes.
shelves = {"plums": 12, "Apples": 40, "pears": 9}
by_name = dict(sorted(shelves.items(), key=lambda pair: pair[0].casefold()))
print(by_name)Questions readers ask
Does sorting change the original dictionary?
No. Sorting builds a new dictionary. The original keeps its old order, so assign the result to a new name if you want to keep it.
Can I sort a dictionary in place?
No. A dictionary has no sort method. Build a new dictionary from sorted pairs instead, as shown above.
Why does an uppercase word sort before a lowercase word?
Plain sorting compares letters by their code values, and uppercase letters come before lowercase ones. Use casefold on the key when you want true alphabetical order.
What happens when two values are equal?
Sorting is stable, so equal values keep their original relative order. Add the key as a second sort field when you want a fixed order for ties.