Back to Blog
Python

Python Sorted Dictionary: Sorting by Key and Value

python sorted dictionary: Learn how to sort a Python dictionary by keys or values using sorted(), and understand ordering behavior in modern Python versions.

pythondictionarysortingsorted()ordereddict
A stylized Python dictionary with keys and values arranged in ascending order, representing a sorted dictionary.

In Python, a dictionary is an unordered collection in the sense that it does not maintain a sorted order of its keys. Even though Python 3.7 and later preserve insertion order, that order reflects the sequence in which items were added, not any logical sorting. To get a python sorted dictionary, you typically call sorted() on the dictionary's items, which returns a list of key-value tuples in the desired order. You can then rebuild a dictionary from that list if you need the result as a dict.

Why a Dictionary Cannot Be Sorted Directly

The dict type does not have a sort() method, and the sorted() function does not mutate the original dictionary. Sorting a dictionary always produces a new sequence, usually a list of tuples, because dictionaries are hash tables and their internal layout is determined by hash values and collision resolution, not by any sort order. This means that the only way to have a "sorted dictionary" is to either create a new dictionary from sorted items or use an alternative data structure like OrderedDict that explicitly remembers insertion order.

Sorting by Key Using sorted()

The simplest way to sort a dictionary by its keys is to pass the dictionary's items to sorted(). The sorted() function compares the first element of each tuple, which is the key, by default.

inventory = {"apple": 5, "banana": 3, "cherry": 8, "date": 1} sorted_items = sorted(inventory.items()) print(sorted_items) # [('apple', 5), ('banana', 3), ('cherry', 8), ('date', 1)]

This returns a list of tuples sorted lexicographically by key. If you need a dictionary that reflects this order, you can pass the list to dict():

sorted_dict = dict(sorted(inventory.items())) print(sorted_dict) # {'apple': 5, 'banana': 3, 'cherry': 8, 'date': 1}

Because Python 3.7+ preserves insertion order, the new dictionary will iterate in the sorted key order. On older Python versions, you would need an OrderedDict to guarantee that behavior.

Sorting by Value Using sorted() with a Key Function

Sorting by value requires specifying a custom key function that extracts the value from each item. The key parameter of sorted() receives each tuple and returns the value to compare.

inventory = {"apple": 5, "banana": 3, "cherry": 8, "date": 1} sorted_by_value = sorted(inventory.items(), key=lambda item: item[1]) print(sorted_by_value) # [('date', 1), ('banana', 3), ('apple', 5), ('cherry', 8)]

Here, item[1] is the value. The result is a list of tuples ordered by the numeric value. You can convert this to a dictionary just like before, but note that if two items have the same value, their relative order will match the original insertion order because sorted() is stable.

Sorting in Descending Order and Handling Ties

To sort in descending order, pass reverse=True to sorted(). This works for both key and value sorting.

sorted_by_value_desc = sorted(inventory.items(), key=lambda item: item[1], reverse=True) print(sorted_by_value_desc) # [('cherry', 8), ('apple', 5), ('banana', 3), ('date', 1)]

When values are equal, you might want a secondary sort criterion, such as the key. You can return a tuple from the key function; Python compares the first element, then the second if there is a tie.

people = {"alice": 30, "bob": 25, "carol": 30, "dave": 25} sorted_people = sorted(people.items(), key=lambda item: (item[1], item[0])) print(sorted_people) # [('bob', 25), ('dave', 25), ('alice', 30), ('carol', 30)]

This sorts first by age, then alphabetically by name within the same age.

Building a Sorted Dictionary Using dict() and OrderedDict

If your code must run on Python versions before 3.7, or if you want to make the intent explicit, use collections.OrderedDict. The OrderedDict preserves the order in which items are inserted, so you can build it from sorted items.

from collections import OrderedDict inventory = {"apple": 5, "banana": 3, "cherry": 8} sorted_ordered = OrderedDict(sorted(inventory.items(), key=lambda item: item[1])) print(sorted_ordered) # OrderedDict([('banana', 3), ('apple', 5), ('cherry', 8)])

In modern Python, dict itself is insertion-ordered, so dict(sorted_items) is usually sufficient. However, OrderedDict still offers methods like move_to_end() that can be useful when you need to reorder items after creation.

Performance and Memory Considerations

Sorting a dictionary has a time complexity of O(n log n) because it relies on comparison-based sorting. The sorted() function creates a list of all items, so it uses O(n) additional memory. For large dictionaries, this can be significant. If you only need to iterate over the dictionary in sorted order once, you can avoid building a new dictionary and just iterate over sorted(d.items()). If you need the sorted order repeatedly, building a dictionary once and reusing it is more efficient than sorting on every access.

There is also a space cost when you convert the sorted list back to a dictionary: the original dictionary and the new dictionary both exist temporarily. If memory is a concern, consider whether you actually need a dictionary or whether a list of tuples is sufficient for your use case.

Common Mistakes and Edge Cases

A frequent mistake is trying to sort a dictionary with mixed key types. For example, {1: 'a', 'b': 2} will raise a TypeError when sorted because Python cannot compare an integer and a string. The same applies to values if you sort by value and they are of incompatible types. Another edge case is sorting by a value that is None; you need to decide how to handle missing or null values, often by providing a default key function like lambda item: item[1] or 0.

When you sort by key, remember that the key function receives the entire item tuple, not just the key. If you want to sort by a specific attribute of a complex key, you need to extract that attribute inside the lambda. For example, if keys are objects with a .name attribute, you would use key=lambda item: item[0].name.

Finally, be aware that sorting a dictionary does not change the original dictionary. If you need the original to remain unsorted, that is fine; if you need the sorted version, you must assign it to a new variable. This is a common source of confusion for developers expecting an in-place operation.

python sorted dictionary: Practical Usage and Code Examples | RYUSLOG DEV