Skip to content

Sorting a Dictionary 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.

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 higher-order functions, such as lambda functions, will also come in handy but isn’t a requirement.

First up, you’ll learn some foundational knowledge before trying to sort a dictionary 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 in dictionaries is guaranteed.

If you wanted to keep an ordered dictionary as a data structure before Python 3.6, you had to use the collections.OrderedDict class. But with the changes in Python 3.6, you can now rely on the insertion order of a regular Python dictionary.

Understanding What Sorting A Dictionary Really Means

When you say “sort a dictionary,” what does that actually mean? In Python, dictionaries are inherently unordered, so sorting a dictionary isn’t about rearranging the items according to a specific order. Instead, it’s about converting the dictionary into a sequence of key-value pairs that are sorted in a specific order.

There are multiple ways you can sort a dictionary in Python. You can sort it based on the keys, values, or even a specific nested attribute. How you sort the dictionary will depend on your specific use case and what kind of data you’re working with.

Sorting Dictionaries in Python

Using the sorted() Function

The simplest way to sort a dictionary is to use the sorted() function. When you pass a dictionary to the sorted() function, it returns a list of tuples, where each tuple contains a key-value pair from the dictionary. These tuples are sorted based on the keys by default.

d = {'apple': 10, 'banana': 5, 'cherry': 20}
sorted_d = sorted(d.items())
print(sorted_d)

Output:

[('apple', 10), ('banana', 5), ('cherry', 20)]

If you want to sort the dictionary based on the values instead of the keys, you can use the key parameter of the sorted() function and provide a lambda function that returns the values.

d = {'apple': 10, 'banana': 5, 'cherry': 20}
sorted_d = sorted(d.items(), key=lambda x: x[1])
print(sorted_d)

Output:

[('banana', 5), ('apple', 10), ('cherry', 20)]

Getting Keys, Values, or Both From a Dictionary

Sometimes, you might only be interested in sorting either the keys or the values of a dictionary. In that case, you can use the keys() or values() methods of a dictionary to get an iterable containing just the keys or the values.

d = {'apple': 10, 'banana': 5, 'cherry': 20}
sorted_keys = sorted(d.keys())
sorted_values = sorted(d.values())
print(sorted_keys)
print(sorted_values)

Output:

['apple', 'banana', 'cherry']
[5, 10, 20]

Understanding How Python Sorts Tuples

When you sort a dictionary using the sorted() function, the resulting list contains tuples. The tuples are sorted based on their first element, then their second element, and so on. This is known as a lexicographic sort.

For example, when sorting a dictionary by keys, if two keys are the same, the tuples with those keys will be sorted based on their values.

d = {'apple': 10, 'banana': 5, 'cherry': 20, 'date': 10}
sorted_d = sorted(d.items())
print(sorted_d)

Output:

[('apple', 10), ('banana', 5), ('cherry', 20), ('date', 10)]

Using the key Parameter and Lambda Functions

If you want to sort a dictionary based on values or a specific nested attribute, you can use the key parameter of the sorted() function. The key parameter takes a callable that is used to extract a comparison key from each element in the iterable.

d = {'apple': {'count': 10}, 'banana': {'count': 5}, 'cherry': {'count': 20}}
sorted_d = sorted(d.items(), key=lambda x: x[1]['count'])
print(sorted_d)

Output:

[('banana', {'count': 5}), ('apple', {'count': 10}), ('cherry', {'count': 20})]

Selecting a Nested Value With a Sort Key

Sometimes, you may have nested dictionaries within your main dictionary, and you want to sort based on a specific attribute of the nested dictionaries. In that case, you can use a lambda function to select the specific nested value and use it as the sort key.

d = {'apple': {'count': 10, 'price': 1.0}, 'banana': {'count': 5, 'price': 0.5}, 'cherry': {'count': 20, 'price': 1.5}}
sorted_d = sorted(d.items(), key=lambda x: x[1]['price'])
print(sorted_d)

Output:

[('banana', {'count': 5, 'price': 0.5}), ('apple', {'count': 10, 'price': 1.0}), ('cherry', {'count': 20, 'price': 1.5}]

Converting Back to a Dictionary

After sorting a dictionary, you might want to convert it back to a dictionary object. To do this, you can use the dict() constructor and pass it the sorted list of tuples.

d = {'apple': 10, 'banana': 5, 'cherry': 20}
sorted_d = sorted(d.items(), key=lambda x: x[1])
sorted_dict = dict(sorted_d)
print(sorted_dict)

Output:

{'banana': 5, 'apple': 10, 'cherry': 20}

Considering Strategic and Performance Issues

When sorting dictionaries, there are some strategic and performance issues that you should consider. Sorting a dictionary can have implications on the performance and speed of your code, especially when dealing with large datasets or frequently updated dictionaries.

Using Special Getter Functions to Increase Performance and Readability

To improve performance and readability when sorting dictionaries based on nested attributes, you can use the operator.itemgetter() function instead of using lambda functions.

from operator import itemgetter
d = {'apple': {'count': 10}, 'banana': {'count': 5}, 'cherry': {'count': 20}}
sorted_d = sorted(d.items(), key=itemgetter(1, 'count'))
print(sorted_d)

Output:

[('banana', {'count': 5}), ('apple', {'count': 10}), ('cherry', {'count': 20})]

Measuring Performance When Using itemgetter()

To understand the performance impact of using itemgetter() instead of lambda functions, you can use the timeit module to time your code and compare the results.

Judging Whether You Want to Use a Sorted Dictionary

Although sorting dictionaries can be useful in certain situations, it’s important to consider whether a sorted dictionary is really the best option for your specific use case. Sorting a dictionary requires additional processing, which can impact the performance of your code. If you frequently update your dictionaries or perform lookups, a different data structure, like a list or a database, might be more suitable.

Comparing the Performance of Different Data Structures

If you’re concerned about the performance of sorting dictionaries, you can compare the performance of different data structures, such as lists or tuples, to determine which one is the fastest and most efficient for your use case.

Comparing the Performance of Sorting

You can also compare the performance of different sorting methods, such as using the sorted() function or itemgetter(), to find the most efficient way to sort your dictionaries.

Comparing the Performance of Lookups

If you frequently perform lookups on your dictionaries, you can compare the performance of accessing values in a sorted dictionary versus other data structures to determine which one provides the fastest lookup times.

Conclusion

In this tutorial, you learned how to sort dictionaries in Python. You reviewed the sorted() function, how to get dictionary views to iterate over, how dictionaries are cast to lists during sorting, how to specify a sort key, and how to rebuild dictionaries using comprehensions or the dict() constructor. You also considered alternative data structures for your key-value data and the strategic and performance issues involved in sorting dictionaries.

By applying the techniques covered in this tutorial, you can effectively sort dictionaries based on keys, values, or nested attributes and optimize the performance of your code.