Skip to content

Effortlessly Sort Dictionary by Value in Python

[

Sorting a Python Dictionary: Values, Keys, and More

by Ian Currie

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.

In this tutorial, you’ll:

  • Review how to use the sorted() function
  • Learn how to get dictionary views to iterate over
  • Understand how dictionaries are cast to lists during sorting
  • Learn how to specify a sort key to sort a dictionary by value, key, or nested attribute
  • Review dictionary comprehensions and the dict() constructor to rebuild your dictionaries
  • Consider alternative data structures for your key-value data

Along the way, you’ll also use the timeit module to time your code and get tangible results for comparing the different methods of sorting key-value data. You’ll also consider whether a sorted dictionary is really your best option, as it’s not a particularly common pattern.

To get the most out of this tutorial, you should know about dictionaries, lists, tuples, and functions. With that knowledge, you’ll be able to sort dictionaries by the end of this tutorial. Some exposure to lambda functions will also come in handy but isn’t a requirement.

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 3.7, that insertion order has been guaranteed.

If you wanted to keep an ordered dictionary as a data structure before Python 3.6, you had to subclass collections.OrderedDict, which maintains the order of insertion.

However, since Python 3.7, dictionaries preserve the order of insertion by default, without the need to use collections.OrderedDict. This means that you can rely on dictionaries maintaining their order without any additional effort.

Understanding What Sorting a Dictionary Really Means

Sorting a dictionary in Python isn’t as straightforward as it might seem at first glance. When you sort a dictionary, you’re usually interested in sorting the items by either the keys or the values.

By default, sorting a dictionary will sort it by its keys, in ascending order. If you want to sort the dictionary by its values, you need to specify a sort key.

It’s important to note that dictionaries in Python are not mutable. In other words, you can’t modify the order of keys or values within a dictionary once it has been created. If you want to change the order of items in a dictionary, you need to create a new dictionary with the desired order.

Sorting Dictionaries in Python

There are several ways to sort dictionaries in Python, depending on what you want to achieve. In this section, you’ll explore different methods and techniques for sorting dictionaries.

Using the sorted() Function

The simplest way to sort a dictionary is by using the sorted() function. This function takes an iterable as input and returns a new sorted list of the elements in ascending order by default.

To sort a dictionary by its keys, you can pass the keys() view of the dictionary as the input to the sorted() function.

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

To sort a dictionary by its values, you can pass the items() view of the dictionary and specify a sort key that extracts the values.

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

Getting Keys, Values, or Both From a Dictionary

Sometimes you might want to iterate over the keys or values of a dictionary without sorting them. Python provides three methods for getting views of a dictionary: keys(), values(), and items().

my_dict = {3: 'c', 1: 'a', 2: 'b'}
keys = my_dict.keys() # Returns a view of the dictionary keys
values = my_dict.values() # Returns a view of the dictionary values
items = my_dict.items() # Returns a view of the dictionary key-value pairs

These views provide a dynamic view of the dictionary’s keys, values, or items, respectively. They can be used to iterate over the dictionary’s contents or to perform operations like sorting.

Understanding How Python Sorts Tuples

When you specify a sort key for a dictionary, you’re essentially telling Python how to sort the tuples that represent the key-value pairs. It’s important to understand how Python sorts tuples so that you can specify the appropriate sort key.

By default, Python compares tuples lexicographically. This means that it compares the first elements of the tuples. If they’re equal, it compares the second elements, and so on.

tuple1 = ('a', 1)
tuple2 = ('b', 2)
tuple3 = ('a', 2)
print(tuple1 < tuple2) # Output: True
print(tuple1 < tuple3) # Output: True

Using the key Parameter and Lambda Functions

To specify a sort key, you can pass the key parameter to the sorted() function or the list.sort() method. The key parameter expects a function that takes an item from the iterable and returns a value that will be used for sorting.

In the case of dictionaries, you can use a lambda function to specify a sort key that extracts the desired value from the key-value pairs.

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

Selecting a Nested Value With a Sort Key

If your dictionary contains nested values and you want to sort based on a specific value within the nested structure, you can use a lambda function with multiple levels of indexing.

my_dict = {1: {'name': 'Alice', 'age': 30}, 2: {'name': 'Bob', 'age': 25}, 3: {'name': 'Charlie', 'age': 35}}
sorted_values = sorted(my_dict.items(), key=lambda x: x[1]['age'])

Converting Back to a Dictionary

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

sorted_items = [('a', 1), ('b', 2), ('c', 3)]
sorted_dict = dict(sorted_items)

Considering Strategic and Performance Issues

While sorting a dictionary can be useful in certain scenarios, it’s important to consider the strategic and performance implications.

Using Special Getter Functions to Increase Performance and Readability

In some cases, you may want to sort a dictionary based on custom logic that is more complex than a simple sort key. Instead of using a lambda function, you can use a specialized getter function such as operator.itemgetter() or operator.attrgetter().

These getter functions provide a more efficient way to sort a dictionary compared to lambda functions because they avoid repeated attribute or key lookups during the sorting process.

Measuring Performance When Using itemgetter()

When sorting large dictionaries, the performance difference between using lambda functions and specialized getter functions such as operator.itemgetter() can be significant. You can measure the performance of different sorting methods using the timeit module.

import timeit
import operator
my_dict = {'Alice': 30, 'Bob': 25, 'Charlie': 35}
def sort_lambda(my_dict):
return sorted(my_dict.items(), key=lambda x: x[1])
def sort_itemgetter(my_dict):
return sorted(my_dict.items(), key=operator.itemgetter(1))
lambda_time = timeit.timeit('sort_lambda(my_dict)', globals=globals(), number=100000)
itemgetter_time = timeit.timeit('sort_itemgetter(my_dict)', globals=globals(), number=100000)
print(f'Lambda time: {lambda_time:.6f} seconds')
print(f'Itemgetter time: {itemgetter_time:.6f} seconds')

Judging Whether You Want to Use a Sorted Dictionary

While sorting a dictionary can be useful in some scenarios, it’s important to consider whether a sorted dictionary is really the best choice for your data. In many cases, alternative data structures like lists, sets, or tuples may be more appropriate.

When deciding whether to use a sorted dictionary, consider the trade-offs between performance, memory usage, and the level of complexity added to your code.

Comparing the Performance of Different Data Structures

To compare the performance of different data structures for storing key-value data, you can use the timeit module to measure the time it takes to execute different operations. For example, you can compare the time it takes to retrieve a value by key from a dictionary, list, and tuple.

import timeit
my_dict = {'Alice': 30, 'Bob': 25, 'Charlie': 35}
my_list = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
my_tuple = (('Alice', 30), ('Bob', 25), ('Charlie', 35))
def dict_lookup():
return my_dict['Alice']
def list_lookup():
return next(item[1] for item in my_list if item[0] == 'Alice')
def tuple_lookup():
return next(item[1] for item in my_tuple if item[0] == 'Alice')
dict_time = timeit.timeit('dict_lookup()', globals=globals(), number=1000000)
list_time = timeit.timeit('list_lookup()', globals=globals(), number=1000000)
tuple_time = timeit.timeit('tuple_lookup()', globals=globals(), number=1000000)
print(f'Dictionary time: {dict_time:.6f} seconds')
print(f'List time: {list_time:.6f} seconds')
print(f'Tuple time: {tuple_time:.6f} seconds')

Comparing the Performance of Sorting

To compare the performance of different sorting methods for dictionaries, you can use the timeit module to measure the time it takes to sort dictionaries of various sizes. This can help you determine the most efficient method for your specific use case.

Comparing the Performance of Lookups

In addition to sorting, you might also want to consider the performance of lookups when choosing a data structure for your key-value data. The time it takes to retrieve a value by key can vary depending on the data structure used.

Conclusion

In this tutorial, you learned different methods and techniques for sorting dictionaries in Python. You explored various ways to use the sorted() function, as well as how to get views of a dictionary to iterate over its keys, values, or items. You also learned about the different ways that Python sorts tuples, and how to specify a sort key to sort a dictionary by value, key, or nested attribute.

Additionally, you discovered how to convert a sorted list back into a dictionary using the dict() constructor. You also considered strategic and performance issues when sorting dictionaries, such as using specialized getter functions to increase performance and readability, and comparing the performance of different data structures.

By understanding these concepts and techniques, you’ll be able to effectively sort dictionaries in Python and choose the most appropriate data structure for your specific needs.