You can sort a dictionary by value in Python using the sorted() function. The sorted() function takes three parameters: object, key, and reverse. Note that in Python 3.7 and later versions, dictionaries are sorted by order of item insertion. For earlier versions, dictionaries are unordered.
Sorting a dictionary makes data easier to retrieve, especially if you want the minimum or maximum value. This tutorial will go through how to sort a dictionary by value with examples.
Table of contents
Sorted Function()
The sorted() function returns a sorted list of the iterable object you pass to it. You can specify whether the list is in ascending or descending order, and it stores strings alphabetically and stores numbers numerically. Note that you cannot sort a list that contains both string and numeric values.
Syntax
sorted(iterable, key=key, reverse=reverse)
Parameter | Description |
---|---|
iterable | Required parameter. The sequence to sort, for example, list, dictionary, tuple etc. |
key | Optional. A function to decide the ordering. Set to None by default. |
reverse | Optional. If set to true, sort the iterable in reverse (descending) order. Set to False by default |
Sort Dictionary Using a for Loop
We can sort a dictionary by values using a for loop. Let’s look at an example of a dictionary containing student grades for an exam. We want to sort the dictionary in ascending order (from lowest to highest value) and print the result to the console.
my_dict = {'student_A':75, 'student_B':50, 'student_C':100, 'student_D':60, 'student_E':90}
sorted_dict = {}
sorted_values = sorted(my_dict.values())
for i in sorted_values:
for j in my_dict.keys():
if my_dict[j] == i:
sorted_dict[j] = my_dict[j]
break
print(sorted_dict)
The above program uses the sorted() function to order the dictionary values. It then loops through the sorted values, finding the key for each value and adds the key-value pairs in the sorted order to a new dictionary called sorted_dict. We have to define a new dictionary because we cannot reorder a dictionary in place in Python. Let’s run the code to get the result:
{'student_B': 50, 'student_D': 60, 'student_A': 75, 'student_E': 90, 'student_C': 100}
Sort Dictionary Using the sorted() Function
We can pass the key argument to the sorted() function, which specifies a function to call on each element in the dictionary before comparing the values for sorting. In the following example, we will use the dictionary.get method on the dictionary to return the value for a given key in the dictionary. Let’s use the same student grade dictionary for this example.
my_dict = {'student_A':75, 'student_B':50, 'student_C':100, 'student_D':60, 'student_E':90}
sorted_dict = {}
sorted_keys = sorted(my_dict, key=my_dict.get) # sorted keys are: [Ghana, China, England, Norway, Italy]
for k in sorted_keys:
sorted_dict[k] = my_dict[k]
print(sorted_dict)
The above program uses sorted(my_dict, key=my_dict.get) to return a list of keys whose values are in ascending order. We can then use a for loop to fill a new dictionary with the sorted key-value pairs. Let’s run the code to see the result:
{'student_B': 50, 'student_D': 60, 'student_A': 75, 'student_E': 90, 'student_C': 100}
Sort Dictionary Using a Lambda Function with sorted()
A lambda function is a small anonymous function that can take any number of arguments but can only have one expression. The syntax for the lambda function is:
lambda arguments : expression
We can use a lambda function to sort a dictionary by value. Let’s look at how to do this with the student grades dictionary.
my_dict = {'student_A':75, 'student_B':50, 'student_C':100, 'student_D':60, 'student_E':90}
sorted_tuples = sorted(my_dict.items(), key=lambda item: item[1])
print(sorted_tuples)
sorted_dict = {k: v for k, v in sorted_tuples}
print(sorted_dict)
The above program passes a lambda function as the key parameter in sorted() to get the value of each item in the dictionary. The result is a sorted collection of key-value pairs. Then the program adds the sorted key-value pairs to a new dictionary. Let’s run the code to see the result:
[('student_B', 50), ('student_D', 60), ('student_A', 75), ('student_E', 90), ('student_C', 100)]
{'student_B': 50, 'student_D': 60, 'student_A': 75, 'student_E': 90, 'student_C': 100}
Sort Dictionary Using operator.itemgetter() with sorted()
We can replace the lambda function with the itemgetter() function from the operator module. This function returns a callable object that returns an item from an object. In our example will pass the itemgetter() function sorted() function as the key parameter. Let’s look at how to do this with the student grades dictionary.
import operator
my_dict = {'student_A':75, 'student_B':50, 'student_C':100, 'student_D':60, 'student_E':90}
sort_list = sorted(my_dict.items(), key=operator.itemgetter(1))
sorted_dict = dict(sort_list)
print(sorted_dict)
Every dictionary has access to the items() method, which returns the key-value pairs of a dictionary as a list of tuples. In the above program, we use the itemgetter() function to get the second element of the tuple or the value of the keys in the dictionary. The result is a sorted list of tuples, which we use to create a new sorted dictionary. Let’s run the code to see the result:
{'student_B': 50, 'student_D': 60, 'student_A': 75, 'student_E': 90, 'student_C': 100}
Using OrderedDict() For Python Versions Lower than 3.7
If we use Python versions lower than 3.7, we have to use the OrderedDict class to preserve a sorted dictionary. The OrderedDict class is available in the collections module. Let’s look at an example of using OrderedDict with the student grades dictionary.
import operator
from collections import OrderedDict
my_dict = {'student_A':75, 'student_B':50, 'student_C':100, 'student_D':60, 'student_E':90}
sorted_tuples = sorted(my_dict.items(), key=operator.itemgetter(1))
sorted_dict = OrderedDict()
for k, v in sorted_tuples:
sorted_dict[k] = v
print(sorted_dict)
The above program declares the sorted_dict variable and assigns an instance of OrderedDict to it. Then, the program adds the sorted key-value pairs to the OrderedDict object. Let’s run the code to see the result:
OrderedDict([('student_B', 50), ('student_D', 60), ('student_A', 75), ('student_E', 90), ('student_C', 100)])
Sort Dictionary By Descending Order
We can use the third parameter in sorted() to change the order of the sorted dictionary. If we set reverse=True, the dictionary will be in the order of descending values. Let’s look at sorting the student grades dictionary in descending order.
my_dict = {'student_A':75, 'student_B':50, 'student_C':100, 'student_D':60, 'student_E':90}
sorted_tuples = sorted(my_dict.items(), key=lambda item: item[1], reverse=True)
sorted_dict = {k: v for k, v in sorted_tuples}
print(sorted_dict)
We set the reverse parameter to true; nothing else in the sorted() call changed. Let’s run the code to see the descending order dictionary:
{'student_C': 100, 'student_E': 90, 'student_A': 75, 'student_D': 60, 'student_B': 50}
Summary
Congratulations on reading to the end of this tutorial! You have gone through how to sort a dictionary by value. The sorted() function allows you to sort a set of data. You can pass a key to the function to execute on each item before making the comparison for sorting. You can use several functions as a key in sorted():
- dictionary.get
- operator.itemgetter()
- lambda function
You can use the reverse parameter in the sorted function to change the sorted order of the dictionary from ascending to descending.
For further reading on dictionaries, go to the articles:
- How to Add to a Dictionary in Python
- How to Check if a Key Exists in a Dictionary in Python
- How to Iterate Over a Dictionary in Python
- How to Create a Nested Dictionary in Python
Go to the Python online courses page to learn more about coding in Python for data science and machine learning.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.