Sort a dictionary by keys or values in Python

Create sorted item lists or dictionaries, handle ties and mixed types, and distinguish insertion order from automatic sorted order.

Best practices
Python programming and application logging

Sort mapping.items() to get an ordered list of key-value pairs. If you need a dictionary, pass that list to dict(): in Python 3.7 and later, dictionaries preserve insertion order.

Sort by key

values = {"c": 3, "a": 1, "b": 2}
items = sorted(values.items(), key=lambda item: item[0])
print(items)  # [('a', 1), ('b', 2), ('c', 3)]

ordered = dict(items)
print(ordered)  # {'a': 1, 'b': 2, 'c': 3}

For ordinary comparable keys, dict(sorted(values.items())) is a shorter form: tuples are compared starting with their first element. If you need only the keys, use sorted(values).

Sort by value

values = {"a": 1, "c": 3, "b": 2}
ascending = dict(sorted(values.items(), key=lambda item: item[1]))
descending = dict(sorted(
    values.items(), key=lambda item: item[1], reverse=True
))
print(list(descending))  # ['c', 'b', 'a']

The original dictionary stays unchanged. If you keep the sorted list of pairs instead, you can iterate in order without rebuilding a dictionary.

Choose a tie-breaker

Sorting is stable: entries with equal values retain their original insertion order. To order equal values by key instead, use a tuple key:

values = {"b": 2, "a": 2, "c": 1}
items = sorted(values.items(), key=lambda item: (item[1], item[0]))
print(items)  # [('c', 1), ('a', 2), ('b', 2)]

The key fields must be mutually comparable. A mixture of numeric and string values can raise TypeError; convert or validate them according to the intended semantics.

A dictionary does not stay sorted automatically

Insertion order is not a sorted-index data structure. Adding a new key puts it at the end, regardless of where it belongs in the earlier sort. Replacing an existing value does not move that key. Sort again when you need a fresh ordering, and use a suitable specialized data structure for repeated range queries.

FAQ

Do I still need OrderedDict? An ordinary dictionary is sufficient when you only need insertion order. OrderedDict remains useful for explicit reordering with move_to_end, popping from either end, and order-sensitive equality between two OrderedDict instances.

Does reverse=True change tie behavior? No. Equal sort keys retain their relative order. Use an explicit secondary key if you want a deterministic tie-breaker independent of insertion history.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting