Skip to content

Sort Dict by Value in Python

[

Sorting a Python Dictionary: Values, Keys, and More

You’ve got a dictionary, but you’d like to sort the key-value pairs. Perhaps you’ve tried passing a dictionary to the sorted() function but haven’t gotten the results you expected. In this tutorial, you’ll go over everything you need to know if you want to sort dictionaries in Python.

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries were inherently unordered. A Python dictionary is an implementation of the hash table, which is traditionally an unordered data structure.

As a side effect of the compact dictionary implementation in Python 3.6, dictionaries started to conserve insertion order. From Python 3.7 onwards, the insertion order of dictionaries is guaranteed.

If you wanted to keep an ordered dictionary as a data structure before Python 3.7, you had to rely on the collections.OrderedDict class. However, if all you need is to sort the dictionary temporarily, you can make use of the sorted() function.

Understanding What Sorting A Dictionary Really Means

Before diving into the different ways to sort a dictionary, let’s understand what sorting a dictionary really means. When you sort a dictionary, you’re actually sorting its keys, values, or both, depending on your requirements.

In Python, dictionaries are inherently unordered. They are optimized for retrieval by key rather than for ordering. So, when we talk about sorting a dictionary, we are essentially transforming the dictionary into a list, where the elements are sorted based on certain criteria.

Sorting Dictionaries in Python

Using the sorted() Function

To sort a dictionary in Python, you can use the sorted() function. The sorted() function returns a new list containing all elements from the original dictionary, sorted in ascending order by default.

For example, let’s say we have a dictionary containing the ages of some people:

ages = {'Alice': 25, 'Bob': 30, 'Charlie': 20}

We can sort this dictionary by the keys (names) using the sorted() function like this:

sorted_ages = sorted(ages)

The resulting sorted_ages list will be ['Alice', 'Bob', 'Charlie'], sorted in alphabetical order.

Getting Keys, Values, or Both From a Dictionary

You can also sort a dictionary by its values using the sorted() function and the key parameter. By default, sorted() will sort the dictionary by its keys, but you can specify a custom function to extract the values for sorting.

For example, let’s say we have a dictionary containing the ages of some people:

ages = {'Alice': 25, 'Bob': 30, 'Charlie': 20}

We can sort this dictionary by the values using the sorted() function and a lambda function as the key parameter:

sorted_ages = sorted(ages, key=lambda x: ages[x])

The resulting sorted_ages list will be ['Charlie', 'Alice', 'Bob'], sorted in ascending order of ages.

If you want to sort the dictionary by both keys and values, you can use the items() method to get a list of key-value pairs and sort it based on your requirements.

Understanding How Python Sorts Tuples

When sorting a dictionary by its values or by both keys and values, Python uses the concept of tuples. Tuples are immutable sequences, and they can be compared element by element.

When sorting a dictionary, each key-value pair is converted into a tuple, and the tuples are compared based on their elements. By default, the comparison is done in ascending order.

For example, let’s say we have a dictionary where the keys are names and the values are ages:

ages = {'Alice': 25, 'Bob': 30, 'Charlie': 20}

To sort this dictionary by its values, Python converts each key-value pair into a tuple and compares them based on their values. The resulting list would be [(Charlie, 20), (Alice, 25), (Bob, 30)].

Using the key Parameter and Lambda Functions

The key parameter of the sorted() function allows you to specify a function that will be applied to the elements of the dictionary before they are compared for sorting.

You can use lambda functions to define the key parameter inline, without the need for a separate function.

For example, let’s say we have a dictionary containing the ages of some people:

ages = {'Alice': 25, 'Bob': 30, 'Charlie': 20}

We can sort this dictionary by the keys (names) in descending order using the sorted() function and a lambda function as the key parameter:

sorted_ages = sorted(ages, key=lambda x: x, reverse=True)

The resulting sorted_ages list will be ['Charlie', 'Bob', 'Alice'], sorted in descending order of names.

Selecting a Nested Value With a Sort Key

If your dictionary contains nested values and you want to sort the dictionary based on a specific nested value, you can use the key parameter and a lambda function to select the nested value as the sort key.

For example, let’s say we have a dictionary containing the ages and favorite colors of some people:

people = {'Alice': {'age': 25, 'color': 'blue'}, 'Bob': {'age': 30, 'color': 'red'}, 'Charlie': {'age': 20, 'color': 'green'}}

We can sort this dictionary based on the age of each person using the sorted() function and a lambda function as the key parameter:

sorted_people = sorted(people, key=lambda x: people[x]['age'])

The resulting sorted_people list will be ['Charlie', 'Alice', 'Bob'], sorted in ascending order of ages.

Converting Back to a Dictionary

Once you have sorted the dictionary, you can convert it back to a dictionary using the dict() constructor or dictionary comprehensions.

For example, let’s say we have a dictionary containing the ages of some people:

ages = {'Alice': 25, 'Bob': 30, 'Charlie': 20}

We can sort this dictionary by the keys (names) and convert it back to a dictionary using a dictionary comprehension:

sorted_ages = {k: ages[k] for k in sorted(ages)}

The resulting sorted_ages dictionary will be {'Alice': 25, 'Bob': 30, 'Charlie': 20}, sorted in alphabetical order of names.

Considering Strategic and Performance Issues

Sorting a dictionary can have strategic and performance implications depending on your specific use case. Before sorting a dictionary, consider the following factors:

Using Special Getter Functions to Increase Performance and Readability

If you need to sort a dictionary by its values frequently, you can use special getter functions such as itemgetter() from the operator module. These getter functions provide a more efficient way of extracting values for sorting compared to lambda functions.

For example, let’s say we have a dictionary containing the ages of some people:

ages = {'Alice': 25, 'Bob': 30, 'Charlie': 20}

We can sort this dictionary by the values using the sorted() function and the itemgetter() function:

from operator import itemgetter
sorted_ages = sorted(ages, key=itemgetter(1))

The resulting sorted_ages list will be ['Charlie', 'Alice', 'Bob'], sorted in ascending order of ages.

Measuring Performance When Using itemgetter()

When using itemgetter() or lambda functions for sorting, it’s important to measure the performance of your code to ensure that it meets your requirements. The timeit module can be used to time your code and compare the performance of different sorting methods.

Judging Whether You Want to Use a Sorted Dictionary

Although sorting a dictionary may seem like a straightforward solution to order your data, it’s important to carefully consider whether a sorted dictionary is the best choice.

Sorting a dictionary can be an expensive operation, especially for large dictionaries. If you only need to access the key-value pairs in a specific order occasionally, it may be more efficient to use other data structures designed for ordered data, such as lists or tuples.

Comparing the Performance of Different Data Structures

If you’re concerned about the performance of sorting operations, you should compare the performance of different data structures to determine the best option for your use case.

You can use the timeit module to measure the time it takes to sort a dictionary, list, or tuple. By comparing the performance of different data structures, you can make an informed decision about which one to use.

Comparing the Performance of Sorting

Sorting a dictionary can impact the performance of your code, especially for large dictionaries. By measuring the performance of different sorting methods, such as using lambda functions or itemgetter(), you can determine which method is more efficient for your specific use case.

Comparing the Performance of Lookups

If you frequently perform lookups on a sorted dictionary, it’s important to consider the impact on performance. Sorting a dictionary changes the order of the keys, which can affect the time it takes to perform lookups.

Conclusion

Sorting a dictionary in Python can be achieved using the sorted() function and specifying a sort key. You can sort a dictionary by its keys, values, or both. However, it’s important to consider the strategic and performance implications of sorting a dictionary, especially for large dictionaries. By measuring the performance of different sorting methods and considering alternative data structures, you can make an informed decision about how to sort and structure your key-value data.