Skip to main content

Sort A Python Dictionary By Value

It is quite common to sort a Python dictionary based on key. But what if you want to perform sorting on the value?

In this article, I’m going to show you multiple ways to sort dictionary value and then return the resultant dictionary.

Method 1: Using operator

The very first method to sort dictionary value is by using sorted(…) function along with operator. So, let’s go ahead and do it as shown below:

import operator
students = {‘Shweta’:25,’Andy’:30,’Maddy’:3}
students = sorted(students.items(), key=operator.itemgetter(1))
print(students)

Method 2: Using lambda

The second method to sort dictionary value is by using sorted(…) function along with lambda and the code looks as shown below::

import operator
students = {‘Shweta’:25,’Andy’:30,’Maddy’:3}
students = sorted(students.items(), key=lambda stud:stud[1])
print(students)

Output

On execution of above two methods, you will get exactly same output.

I hope you enjoyed sorting your dictionary values in Python. If you have reached till here, do not forget to take a look at the video recoding of this sample code on my YouTube channel and make sure to subscribe it:




Comments