Sorting Dictionary by Value in Python


Table of Contents

This python program sorts dictionary on the basis of value in ascending and descending order.

While programming, it is often require to sort dictionary data either in ascending or descending order based on key or value. In this programming examples, we sort dictionary data on the basis of value.

To sort dictionary in python lamda function is very useful. In this example, we use lambda function to sort a dictionary by value.

Consider we have following dictionary:


# Dictionary for item and price
# item as key & price as value

data = {'sugar': 80,'tea leaf': 200,'corn flakes': 60,'powder milk':120}

And, we want to sort this dictionary by price.

Sorting Dictionary by Value in Ascending Order


# Dictionary for item and price
# item as key & price as value
data = {'sugar': 80,'tea leaf': 200,'corn flakes': 60,'powder milk':120}

# Sorting on the basis of value in ascending order
sorted_result = sorted(data.items(), key = lambda x:(x[1]))

print(sorted_result)

Output

[('corn flakes', 60), ('sugar', 80), ('powder milk', 120), ('tea leaf', 200)]

Sorting Dictionary by Value in Descending Order


# Dictionary for item and price
# item as key & price as value
data = {'sugar': 80,'tea leaf': 200,'corn flakes': 60,'powder milk':120}

# Sorting on the basis of value in descending order
sorted_result = sorted(data.items(), key = lambda x:(x[1]), reverse=True)

print(sorted_result)

Output

[('tea leaf', 200), ('powder milk', 120), ('sugar', 80), ('corn flakes', 60)]