Python: How to sort a dictionary by key or value (4 examples)

Updated: February 13, 2024 By: Guest Contributor Post a comment

Overview

Dictionaries in Python are inherently unordered prior to Python 3.7. However, Python 3.7 and later versions remember the order of items inserted. Despite this feature, there are numerous situations where one needs to sort a dictionary by its keys or values for various purposes such as data analysis, organization of information, or simply to improve readability. This article provides a step-by-step guide on how to sort dictionaries in Python using both basic and advanced techniques, topped with multiple examples to illustrate each method.

Sorting by Keys

Sorting a dictionary by its keys is straightforward. The simplest way to achieve this is by using the sorted() function, which returns a list of the sorted keys. You can then use a dictionary comprehension to create a new sorted dictionary.

Example 1: Sorting by keys

my_dict = {'banana': 3, 'apple': 2, 'pear': 1, 'orange': 4}
dict_sorted_by_keys = {key: my_dict[key] for key in sorted(my_dict)}
print(dict_sorted_by_keys)

Outpu:

{'apple': 2, 'banana': 3, 'orange': 4, 'pear': 1}

Sorting by Values

Sorting a dictionary by values requires extracting the values along with keys, sorting them, and then rebuilding the dictionary. You can use a lambda function as the key argument in the sorted() function to achieve this.

Example 2: Sorting by values

my_dict = {'banana': 2, 'apple': 4, 'pear': 1, 'orange': 3}
sorted_by_value = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_by_value)

Output:

{'pear': 1, 'banana': 2, 'orange': 3, 'apple': 4}

Advanced Sorts

For more complex sorting needs, such as sorting by the values but in descending order or sorting based on a custom function, Python offers additional flexibility.

Example 3: Sorting by values in descending order


my_dict = {'banana': 2, 'apple': 4, 'pear': 1, 'orange': 3}
sorted_descending = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print(sorted_descending)

Output:

{'apple': 4, 'orange': 3, 'banana': 2, 'pear': 1}

In advanced scenarios, you might want to sort dictionaries based on a custom logic. One common practice is to sort a dictionary by the length of its keys. This can be achieved by passing an appropriate function to the sorted() key parameter.

Example 4: Sorting by the length of the keys


my_dict = {'banana': 3, 'a': 5, 'pear': 2, 'orange': 4}
sorted_by_key_length = dict(sorted(my_dict.items(), key=lambda item: len(item[0])))
print(sorted_by_key_length)

Output:

{'a': 5, 'pear': 2, 'banana': 3, 'orange': 4}

The versatility of sorting mechanisms in Python allows for myriad sorting practices beyond what’s detailed here, such as sorting by composite keys or applying secondary sort criteria. As you delve deeper into Python’s capabilities, you’ll discover even more sophisticated methods for sorting dictionaries to fit any scenario.

Conclusion

Sorting dictionaries by keys or values in Python is not merely for esthetic optimization but often a necessity for data manipulation and analysis. With the understanding of basic to advanced sorting methods outlined in this article, you’re now equipped to handle a wide array of sorting requirements, enhancing your Python scripts’ efficiency and readability. Remember, the simplicity or complexity of the method chosen should align with the specific needs of your project or task.