Skip to content

Effortlessly Sort Dictionary by Value in Python

[

Sorting a Python Dictionary: Values, Keys, and More

You have a dictionary in Python, but you want to sort the key-value pairs. If you’ve tried using the sorted() function with a dictionary and didn’t get the expected results, don’t worry. In this tutorial, we will go over everything you need to know about sorting dictionaries in Python.

Table of Contents

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries in Python were inherently unordered. The implementation of dictionaries in Python is based on hash tables, which traditionally are unordered data structures.

However, starting from Python 3.6, dictionaries started to conserve insertion order due to the compact dictionary implementation. Since Python 3.7, the insertion order of dictionaries has been guaranteed.

If you wanted to preserve the order of a dictionary before Python 3.6, you would use the collections.OrderedDict class. But now, you can rely on the built-in dictionary type to maintain the order of the key-value pairs.

Understanding What Sorting a Dictionary Really Means

When it comes to sorting a dictionary, it’s essential to understand what sorting actually means in this context.

Sorting a dictionary refers to sorting the dictionary based on either the keys, the values, or both.

Sorting a dictionary by keys means arranging the key-value pairs in ascending or descending order based on the keys of the dictionary.

Sorting a dictionary by values means arranging the key-value pairs in ascending or descending order based on the values of the dictionary.

Sorting a dictionary by both keys and values means arranging the key-value pairs in ascending or descending order based on the keys first and then the values in case of a tie.

Sorting Dictionaries in Python

Now that you understand the concept of sorting a dictionary, let’s explore different ways to achieve this in Python.

Using the sorted() Function

The most straightforward way to sort a dictionary in Python is to use the sorted() function. The sorted() function takes an iterable and returns a new list with the items sorted in ascending order.

To sort a dictionary by keys, you can pass the dictionary’s keys() method to the sorted() function:

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = sorted(my_dict.keys())

To sort a dictionary by values, you can pass the items() method of the dictionary to the sorted() function and specify the key parameter as lambda item: item[1]:

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = sorted(my_dict.items(), key=lambda item: item[1])

To sort a dictionary by both keys and values, you can pass the items() method of the dictionary to the sorted() function and specify multiple key parameters:

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = sorted(my_dict.items(), key=lambda item: (item[0], item[1]))

Getting Keys, Values, or Both From a Dictionary

In some cases, you might only need the keys, values, or both from a dictionary and not the entire sorted key-value pairs.

To get the keys from a dictionary in sorted order, you can use the sorted() function with the keys() method:

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_keys = sorted(my_dict.keys())

To get the values from a dictionary in sorted order, you can use the sorted() function with the values() method:

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_values = sorted(my_dict.values())

To get both the keys and values from a dictionary in sorted order, you can use the sorted() function with the items() method:

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_items = sorted(my_dict.items())

Understanding How Python Sorts Tuples

When sorting a dictionary, you might encounter situations where the values are the same for multiple keys. In such cases, Python uses the natural sort order of the tuples to determine the final sort order.

The natural sort order compares the elements of the tuples in the order they appear. If the first elements of two tuples are the same, then the second elements are compared, and so on.

For example, consider the following dictionary:

my_dict = {'c': 3, 'b': 2, 'a': 1, 'd': 3}

When sorting this dictionary, the keys 'c' and 'd' have the same value of 3. In this case, Python will sort these keys based on their natural sort order. Since 'c' comes before 'd' in the alphabetic order, the resulting sorted dictionary will be:

{'c': 3, 'd': 3, 'a': 1, 'b': 2}

Using the key Parameter and Lambda Functions

The sorted() function allows you to specify a key parameter, which is a function that will be used to extract a comparison key from each item. This comparison key is then used to determine the sort order.

To sort a dictionary by values in descending order, you can pass a lambda function to the key parameter and multiply the values by -1:

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = sorted(my_dict.items(), key=lambda item: item[1] * -1)

Selecting a Nested Value With a Sort Key

Sometimes, you might have a dictionary with nested values, and you want to sort the dictionary based on a specific attribute of the nested values. In such cases, you can use lambda functions with multiple indexing to select the desired attribute as the sort key.

Consider the following dictionary with nested values:

my_dict = {'a': {'name': 'Alice', 'age': 25}, 'b': {'name': 'Bob', 'age': 30}, 'c': {'name': 'Charlie', 'age': 20}}

Suppose you want to sort this dictionary based on the 'age' attribute of the nested values. You can use a lambda function with multiple indexing to achieve this:

sorted_dict = sorted(my_dict.items(), key=lambda item: item[1]['age'])

Converting Back to a Dictionary

After sorting a dictionary, the result is typically a list of tuples representing the key-value pairs in sorted order. If you want to convert this list back into a dictionary, you can use the dict() constructor.

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_items = sorted(my_dict.items())
sorted_dict = dict(sorted_items)

Considering Strategic and Performance Issues

When sorting dictionaries, there are strategic and performance issues that you should consider.

Using Special Getter Functions to Increase Performance and Readability

In certain scenarios, the operator.itemgetter() function can provide a more efficient and readable way to sort dictionaries.

from operator import itemgetter
my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = sorted(my_dict.items(), key=itemgetter(1))

Measuring Performance When Using itemgetter()

When considering performance, it’s important to measure the execution time of your code. The timeit module in Python can be used to time your code and compare the performance of different approaches.

Judging Whether You Want to Use a Sorted Dictionary

Even though sorting a dictionary by value might seem like a useful feature, it is not a common pattern. It’s important to consider whether a sorted dictionary is really necessary for your specific use case.

Comparing the Performance of Different Data Structures

When working with large datasets, using alternative data structures like databases or specialized libraries might be more efficient than sorting dictionaries.

Comparing the Performance of Sorting

Sorting a dictionary can be an expensive operation, especially for large dictionaries. It’s important to measure the performance of sorting in your specific scenario to ensure it meets your performance requirements.

Comparing the Performance of Lookups

If you frequently need to look up values by key, sorting a dictionary might not be the most efficient solution. In such cases, consider using other data structures like hash maps or trees that provide faster lookup times.

Conclusion

Sorting a dictionary in Python can be achieved using the sorted() function with various techniques like specifying sort keys, using lambda functions, and utilizing the itemgetter() function. However, it’s important to consider the strategic and performance implications of sorting dictionaries, as it’s not a common pattern and might not always be the most efficient solution for your specific use case.

So there you have it—the complete guide to sorting dictionaries in Python. With the techniques and considerations discussed in this tutorial, you have the tools to sort key-value pairs efficiently and effectively in your Python programs.