Skip to content

Sort Python Dictionary by Values

[

Sorting a Python Dictionary: Values, Keys, and More

If you have a dictionary in Python and you want to sort its key-value pairs, there are several methods you can use. In this tutorial, we will cover everything you need to know about sorting dictionaries in Python.

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries in Python were unordered. They were implemented using hash tables, which are traditionally unordered data structures. However, starting from Python 3.6, dictionaries started conserving the insertion order, and from Python 3.7, the order of dictionaries is guaranteed.

Understanding What Sorting A Dictionary Really Means

When it comes to sorting a dictionary, it’s important to understand what exactly you are sorting. A dictionary consists of key-value pairs, and sorting a dictionary can mean sorting either the keys, the values, or both.

Sorting Dictionaries in Python

There are several methods you can use to sort dictionaries in Python:

Using the sorted() Function

The sorted() function can be used to sort a dictionary based on its keys or values. By default, sorted() returns a list of the dictionary’s keys in ascending order.

my_dict = {"c": 3, "a": 1, "b": 2}
sorted_keys = sorted(my_dict)
print(sorted_keys) # Output: ['a', 'b', 'c']
sorted_values = sorted(my_dict.values())
print(sorted_values) # Output: [1, 2, 3]

Getting Keys, Values, or Both From a Dictionary

You can also retrieve the keys, values, or both from a dictionary using the keys(), values(), and items() methods, respectively.

my_dict = {"c": 3, "a": 1, "b": 2}
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()

Understanding How Python Sorts Tuples

When sorting a dictionary’s items, Python uses the built-in comparison operators to compare the tuples representing the key-value pairs. This means that by default, Python will first compare the keys and then the values if the keys are equal.

Using the key Parameter and Lambda Functions

You can specify a custom sort key using the key parameter of the sorted() function. The key parameter accepts a function that takes an item from the iterable being sorted and returns a value used for sorting.

my_dict = {"c": 3, "a": 1, "b": 2}
sorted_dict = sorted(my_dict.items(), key=lambda x: x[1])
print(sorted_dict) # Output: [('a', 1), ('b', 2), ('c', 3)]

Selecting a Nested Value With a Sort Key

If your dictionary contains nested data structures, such as dictionaries or lists, you can use a lambda function to select a specific nested value as the sort key.

my_dict = {"c": {"d": 4}, "a": {"e": 1}, "b": {"f": 2}}
sorted_dict = sorted(my_dict.items(), key=lambda x: x[1]["f"])
print(sorted_dict) # Output: [('a', {'e': 1}), ('b', {'f': 2}), ('c', {'d': 4})]

Converting Back to a Dictionary

After sorting a dictionary, you might want to convert it back to a dictionary. You can achieve this by using a dictionary comprehension or the dict() constructor.

my_dict = {"c": 3, "a": 1, "b": 2}
sorted_dict = {k: v for k, v in sorted(my_dict.items())}
print(sorted_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
sorted_dict2 = dict(sorted(my_dict.items()))
print(sorted_dict2) # Output: {'a': 1, 'b': 2, 'c': 3}

Considering Strategic and Performance Issues

Sorting a dictionary can have strategic and performance implications. Here are some considerations you should keep in mind:

Using Special Getter Functions to Increase Performance and Readability

If you are sorting a large dictionary multiple times, using special getter functions, such as the itemgetter() function from the operator module, can increase both performance and readability.

from operator import itemgetter
my_dict = {"c": 3, "a": 1, "b": 2}
getter = itemgetter(1)
sorted_dict = sorted(my_dict.items(), key=getter)
print(sorted_dict) # Output: [('a', 1), ('b', 2), ('c', 3)]

Measuring Performance When Using itemgetter()

If performance is a critical factor, you can measure the performance of different sorting methods using the timeit module.

import timeit
from operator import itemgetter
my_dict = {"c": 3, "a": 1, "b": 2}
def sort_with_itemgetter():
getter = itemgetter(1)
return sorted(my_dict.items(), key=getter)
print(
timeit.timeit(sort_with_itemgetter, number=100000)
) # Output: 1.0113561999999996

Judging Whether You Want to Use a Sorted Dictionary

While sorting a dictionary can be useful in some scenarios, it’s not a common pattern in Python. Consider whether a sorted dictionary is really the best option for your use case or if there is a more suitable data structure available.

Comparing the Performance of Different Data Structures

If you frequently need to perform sorting operations on key-value data, consider using alternative data structures, such as lists of tuples or namedtuples, which are optimized for sorting.

Comparing the Performance of Sorting

If performance is critical and you’re dealing with large amounts of data, compare the performance of different sorting methods, such as the sorted() function, dictionary comprehensions, or the dict() constructor.

Comparing the Performance of Lookups

When working with large dictionaries, consider the performance implications of lookups. In some cases, using a different data structure, such as a database or a specialized data storage solution, might be more efficient.

Conclusion

Sorting a dictionary in Python can be achieved using various methods, including the sorted() function, dictionary views, and lambda functions as sort keys. It’s important to consider the performance and strategic implications of sorting a dictionary and choose the most suitable method for your use case.