Sort a dictionary by value

Posted in Python by Dirk - last update: Jan 04, 2024

In Python, a dictionary is a built-in data type that represents a collection of key-value pairs. It is a versatile and mutable container that allows you to store and retrieve values based on unique keys. Dictionaries are also known as associative arrays, maps, or hash maps in other programming languages.

Dictionaries are unordered, meaning that the order in which items are stored is not guaranteed. Starting from Python 3.7, the insertion order of items is maintained, this is not the case for earlier versions of Python

As a result, sorting a dictionary by value (where the ordered result is still a dictionary) is only possible as of Python 3.7. For earlier versions, you can only get a representation of an ordered dictionary, not as a dictionary but as an ordered data type like a list,

Using sorted() with lambda function

In Python, you can use the sorted() function along with a lambda function as the key parameter to sort a dictionary by its values.

Here’s an example:

my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}

# Sorting the dictionary by values in ascending order
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

print(sorted_dict)

This will output:

{'grape': 1, 'banana': 2, 'apple': 5, 'orange': 8}

In this example, sorted() is used with the key parameter set to a lambda function that returns the second element of each key-value pair (i.e., the values). If you want to sort in descending order, you can add the reverse=True parameter:

sorted_dict_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))

print(sorted_dict_desc)

This will output:

{'orange': 8, 'apple': 5, 'banana': 2, 'grape': 1}

This sorts the dictionary by values in descending order.

Using the itemgetter from the operator module

itemgetter is a function from the operator module in Python. It creates a callable object that can be used as the key function for sorting or retrieving elements from an iterable.

itemgetter(n) returns a function that takes an iterable object as input and retrieves the n-th element from each item.

from operator import itemgetter

my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}

# Sorting the dictionary by values in ascending order
sorted_dict = dict(sorted(my_dict.items(), key=itemgetter(1)))

print(sorted_dict)

This code achieves the same result as the lambda function in the previous example. The itemgetter(1) retrieves the second element of each key-value pair for sorting.

Other articles