How to Sort a Dictionary by Value in Python

In python, we have discussed many concepts on Dictionary. But sometimes, we come to a situation where we need to sort the dictionary by its value. In this tutorial, we will be discussing how to sort a dictionary by value in python.

What is dictionary?

Dictionary in Python is an unordered collection of data values, used to store the data values like a map, unlike other Data Types that hold only a single value as an element. It holds the key: value pair, which is provided to make the dictionary more optimized. Dictionary is mutable in nature, which says that changes can be done after declaring it. It allows duplicate entries. We declare dictionary in curly braces { }.

What is sorting?

Sorting means sequentially arranging the values, like ascending order or descending order.

Need of sorting a dictionary

  • A dictionary has an O(1) search time complexity which is best in comparison between list, tuple, etc.
  • A sorted dictionary gives a better understanding of the concepts and clarity in handling the operations.
  • Sorting helps us to make efficient analyses while we are working with any data structure.

5 Ways to sort a dictionary by value in Python

Here, we will be discussing all the different ways through which we can sort a dictionary by value:

1. Using a sorted() with operator module

In this example, we will be using the sorted() function and applying the itemgetter() function from the operator module. This function will sort the dictionary in the form of a list of tuples which will be sorted according to the second element in the tuple. After that, we will be applying the dict() function to convert it again into the dictionary. If you want to sort a dictionary in descending order, you need to write reverse = True inside the function. Let us look at the example for understanding the concept in detail.

#import operator module
import operator

dic = {'python' : 3, 'pool' : 5, 'solution' : 6, 'sid' : 1}
print("Input dictionary : ",dic)
sort = sorted(dic.items(), key=operator.itemgetter(1))

output = dict(sort)
print("Output sorted dictionary : ",output)

Output:

Input dictionary :  {'python': 3, 'pool': 5, 'solution': 6, 'sid': 1}
Output sorted dictionary :  {'sid': 1, 'python': 3, 'pool': 5, 'solution': 6}

Explanation:

  • Firstly, we will import the operator module.
  • Then, we will take the input dictionary in the variable named dic.
  • After that, we have printed the input dictionary.
  • Then, we have applied the sorted function inside which we have given two parameters as the values of the dictionary and the key = operator.itemgetter(1). Here, 1 represents the values of the dict, and 0 represents the values of the keys.
  • Then, we have converted the list of tuples into the dictionary with the help dict function and stored the output in the output variable.
  • Hence, you can see the sorted dictionary.

2. Using sorted() function with lambda() function to sort a dictionary by value in Python

In this example, we will be using the sorted() function, which will be clubbed with the lambda() function, which will sort the dictionary by value. Lambda() function is used to create the anonymous function, i.e., a function without the name. It will help to optimize the code. If you want to sort a dictionary in descending order, you need to write reverse = True inside the function. Let us look at the example for understanding the concept in detail.

dic = {'python' : 3, 'pool' : 5, 'solution' : 6, 'sid' : 1}
print("Input dictionary : ",dic)

sort = sorted(dic.items(), key=lambda item: item[1])
output = dict(sort)
print("Output sorted dictionary : ",output)

Output:

Input dictionary :  {'python': 3, 'pool': 5, 'solution': 6, 'sid': 1}
Output sorted dictionary :  {'sid': 1, 'python': 3, 'pool': 5, 'solution': 6}

Explanation:

  • Firstly, we will take the input dictionary in the variable named dic.
  • After that, we have printed the input dictionary.
  • Then, we have applied the sorted() function with both the parameters as dic.items() and key = lambda item: item[1]. in this, also 1 is treated for the values of the input dictionary.
  • Then, we have converted the list of tuples into the dictionary with the help dict function and stored the output in the output variable.
  • Hence, you can see the sorted dictionary.

3. Using sorted() function with dict.items() to sort a dictionary by value in Python

In this example, we will be using the sorted() function, which will be clubbed with dict.items() function. Dict.items() function is used to fetch the keys/values from a dictionary. If you want to sort a dictionary in descending order, you need to write reverse = True inside the function. Let us look at the example for understanding the concept in detail.

dic = {'python' : 3, 'pool' : 5, 'solution' : 6, 'sid' : 1}
print("Input dictionary : ",dic)

output = dict(sorted((value, key) for (key,value) in dic.items()))
print("Output sorted dictionary : ",output)

Output:

Input dictionary :  {'python': 3, 'pool': 5, 'solution': 6, 'sid': 1}
Output sorted dictionary :  {1: 'sid', 3: 'python', 5: 'pool', 6: 'solution'}

Explanation:

  • Firstly, we will take the input dictionary in the variable named dic.
  • After that, we have printed the input dictionary.
  • Then, we have applied the dict() function for converting the list of tuples into the dictionary.
  • Inside the dict() function, we have applied the sorted() function, and inside it, we have applied all the required parameters.
  • Hence, you can see the sorted dictionary.

4. Using sorted() function and return an ordered dictionary

In this example, we will import orderedDict from the collections module. Then, we will use orderedDict() function clubbed with the sorted() function. If you want to sort a dictionary in descending order, you need to write reverse = True inside the function. Let us look at the example for understanding the concept in detail.

#import OrderedDict from collections module
from collections import OrderedDict

dic = {'python' : 3, 'pool' : 5, 'solution' : 6, 'sid' : 1}
print("Input dictionary : ",dic)

output = OrderedDict(sorted(dic.items(), key=lambda x: x[1]))
print("Sorted dictionary : ",output)

Output:

Input dictionary :  {'python': 3, 'pool': 5, 'solution': 6, 'sid': 1}
Sorted dictionary :  OrderedDict([('sid', 1), ('python', 3), ('pool', 5), ('solution', 6)])

Explanation:

  • Firstly, we will import the OrderedDict function from the collections module.
  • Then, we will take the input dictionary in the variable named dic.
  • After that, we have printed the input dictionary.
  • After that, we have applied the orderedDict() function inside which we have applied the sorted() function.
  • Inside, which we have applied two parameters as dic.items() and lambda function.
  • Hence, you can see the sorted dictionary as the output.

5. Using for Loop to sort a dictionary by value in Python

In this example, we will be sorting a dictionary by using the for loop. If you want to sort a dictionary in descending order, you need to write reverse = True inside the function. Let us look at the example for understanding the concept in detail.

dic = {'python' : 3, 'pool' : 5, 'solution' : 6, 'sid' : 1}
print("Input dictionary : ",dic)

sorted_values = sorted(dic.values()) # Sort the values
sorted_dict = {}

for i in sorted_values:
    for k in dic.keys():
        if dic[k] == i:
            sorted_dict[k] = dic[k]
            break

print("Sorted dictionary : ",sorted_dict)

Output:

Input dictionary :  {'python': 3, 'pool': 5, 'solution': 6, 'sid': 1}
Sorted dictionary :  {'sid': 1, 'python': 3, 'pool': 5, 'solution': 6}

Explanation:

  • Firstly, we will take the input dictionary in the variable named dic.
  • After that, we have printed the input dictionary.
  • Then, we have sorted the values of the input dictionary with the help of the sorted function.
  • We have taken an empty dictionary with the name sorted_dict{ }.
  • After that, we have applied for loop up to the range of sorted_values.
  • Inside it again a for loop and inside an if condition, which will check the condition and store the output in the empty dictionary.
  • At last, we have printed the empty dictionary.
  • Hence, you can see the sorted dictionary as the output.

Conclusion

In this tutorial, we have learned about the concept of the sort a dictionary by value. We have seen what a dictionary is and what is sorting. We have also discussed what the need for sorting the dictionary is. After that, we have discussed all the through which we can sort the dictionary by value. All the ways are explained in detail with the help of examples. You can use any of the functions according to your choice and your requirement in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Subscribe
Notify of
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Bajusz Tamás
Bajusz Tamás
3 years ago
Pratik Kinage
Admin
3 years ago
Reply to  Bajusz Tamás

Hi,

Yes, this module can also be used to sort dict by value. However, I don’t recommend installing a whole module to sort a dictionary. You can simply use 2-3 lines of code provided in the post to achieve it.

Regards,
Pratik

Bajusz Tamás
Bajusz Tamás
3 years ago
Reply to  Pratik Kinage

It depends on your use case. If your dict is changing over the time, and you need to access its values any time, this module is the way to go. I use it to keep leader boards up to date in my chess variant server: Pychess.org(/)players

Pratik Kinage
Admin
3 years ago
Reply to  Bajusz Tamás

Yes, correct. I agree with your point here. It’s an easy plug-and-go module.
If your dictionary changes over time, it’ll be a little more tricky for new programmers to handle the changes. This module is definitely useful when your dict changes over time.

Regards,
Pratik