How to sort a dictionary by values in python

Let’s say you have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key to the dictionary.

Sort a dictionary by value in python

Let’s say you have a dictionary x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} and you want to sort it by using the value.

To sort a dictionary by value in python, use the sorted() function along with the lambda expression. It will sort out all the dictionaries by their value not keys.

Here is the python code that does exactly what we have described. We have used the sorted() function and the item() function.

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_dict={k: v for k, v in sorted(x.items(), key=lambda item: item[1])}

Output of the code

{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

The Most Simplest way to sort a Dictionary by its values

TO sort a dictionary by its value in python, Then follow the following steps:

Step No 1: get the Values of Dict

Step No 2: sort the items in the dictionary by using the values

Here is a quick python example that explains how to sort a python dictionary by its values.

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_dict=dict(sorted(x.items(), key=lambda item: item[1]))

Output of the code

{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

Bonus 1: Sort a Python dictionary by its value

If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as:

from collections import defaultdict
d = defaultdict(int)
for w in text.split():
    d[w] += 1
for w in sorted(d, key=d.get, reverse=True):
  print(w, d[w])

Bonus 2: Sort a Python dictionary in Ascending order by its value

Use the python function sorted(d.items(), key=lambda x: x[1]) to sort a dictionary in ascending order by its values.

d={1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
a_d=sorted(d.items(), key=lambda x: x[1])

Bonus 3: Sort a python Dictionary in descending order

To sort it in descending order just add reverse=True:

d = {'one':1,'three':3,'five':5,'two':2,'four':4}
a = sorted(d.items(), key=lambda x: x[1], reverse=True)    

Summary and conclusion

IN this python article, you have seen different methods for sorting a dictionary by its values. If you have any questions please let me know in the comment section.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top