3 Ways to sort a Dictionary by Value in Python

sokacoding
4 min readJan 30, 2023

--

Hello fellow Coders!

You may have come across the case where you want to sort a dictionary by its value. In Python there are several ways to do so, and in this article we’ll look at three possible methods. Whether you are a beginner or an experienced Python programmer, these methods will help you sort dictionaries quickly and easily. There is no best option to choose but there are certain situations in which one of the options is more useful than the other. This depends on the design of your program. In this article we will be working with the following dictionary.

my_dict = {'five': 5, 'two': 2, 'one': 1, 'three': 3, 'four': 4}

Our goal is to sort this dictionary by its values as follows.

my_dict = {'one': 1, 'two': 2, 'moin': 2, 'three': 3, 'four': 4, 'five': 5}

Exploring the Python built-in sorted() function

If we pass only the dictionary to the function, it will be sorted by the keys. in our case, the keys will thus be sorted alphabetically.

print(sorted(my_dict))
>>> ['five', 'four', 'one', 'three', 'two']

Note that the sorted() function returns a list, but we want to create a sorted dictionary. Nevertheless we can use this function by applying a certain parameter. If we use the key parameter, we can tell the function what to sort the keys by. The keyparameter expects a function itself as a passing value. We can obtain the value of an associated key by calling my_dict.get('one'). Knowing this we can modify our command using the key parameter like this.

my_sorted_keys = sorted(my_dict, key=my_dict.get)

print(my_sorted_keys)
>>> ['one', 'two', 'three', 'four', 'five']

Now we have a list of the corresponding keys sorted by its values. We are getting closer to our goal. We can now additionally create a sorted list of the values.

my_sorted_values = sorted(my_dict.values())

print(my_sorted_values)
>>> [1, 2, 3, 4, 5]

If you have read my article 6 Ways to initialize a Dictionary in Python you know that we can easily convert those two lists to the desired dictionary.

my_sorted_dict = dict(zip(my_sorted_keys, my_sorted_values))

print(my_sorted_dict)
>>> {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

Using sorted(), dict.items() and a lambda function

First, we convert our dictionary into a list of tuples that contain our key-value pairs using the dict.items() function. This function returns an object of type dict_items. We get our desired list by passing this object to the list() function. Let’s look at this in detail.

# my_items is an object of type 'dict_items'
my_items = my_dict.items()

# check the type
print(type(my_items)
>>> <class 'dict_items'>

# the object contains the list of key-value pairs
print(my_items)
>>> dict_items([('five', 5), ('two', 2), ('one', 1), ('three', 3), ('four', 4)])


# we pass 'my_items' into the list() function
my_list_of_tuples = list(my_items)

# check the type
print(type(my_list_of_tuples)
>>> <class 'list'>

# now we have a list of tuples
print(my_list_of_tuples)
>>> [('five', 5), ('two', 2), ('one', 1), ('three', 3), ('four', 4)]

Note that the sorted() function can work with the my_items object without converting it into a list. However, you cannot treat the object as a list. It is not subscriptable. I just want to make sure you know what is happening at every stage.

# my_items of type 'dict_items'
my_items = my_dict.items()

# trying to read the 3rd tuple of the list inside of the object
print(my_items[2])

>>> Traceback (most recent call last):
File "dictionaries.py", line 11, in <module>
print(my_items[2])
TypeError: 'dict_items' object is not subscriptable

As just mentioned we can pass the dict_items object into the sorted() function. But if we do this without specifying the key parameter it leaves us with a list of tuples sorted by the first value of the tuple. It is sorted alphabetically.

my_sorted_items = sorted(my_dict.items())

print(my_sorted_items)
>>> [('five', 5), ('four', 4), ('one', 1), ('three', 3), ('two', 2)]

Now lambda functions come in handy. We assign a lambda function to the key parameter of sorted() telling it to use the second entry of the elements to be sorted.

my_sorted_list_of_tuples = sorted(my_dict.items(), key=lambda x: x[1])
print(my_sorted_list_of_tuples)
>>> [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]

You can think of it as the sorted()function passing each tuple to x and sorting the tuples by x[1]. The final step is to convert our sorted list of tuples back into a dictionary.

my_sorted_dict = dict(my_sorted_list_of_tuples)
print(my_sorted_dict)
>>> {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

Using sorted() and dictionary comprehension

We have already determined how to get the keys sorted by value.

my_sorted_keys = sorted(my_dict, key=my_dict.get)

print(my_sorted_keys)
>>> ['one', 'two', 'three', 'four', 'five']

We will use this list of sorted keys inside of dictionary comprehension.

my_sorted_keys = sorted(my_dict, key=my_dict.get)

my_sorted_dict = {key: my_dict[key] for key in my_sorted_keys}

print(my_sorted_dict)
>>> {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

A new dictionary is being created using the keys of my_sorted_keys. The keys are now in the correct order. Each key is assigned to the corresponding value of my_dict. At the end we get the sorted dictionary.

Conclusion

Sorting a dictionary by its values might seem tricky. I hope that this article has given you a comprehensive overview of different ways to sort a dictionary by its value in Python. Thanks for reading and feel free to drop a comment!

--

--

sokacoding

M.Sc. Media Informatics. Scientific Associate at Hochschule Düsseldorf - University of Applied Sciences.