how to sort a dictionary by value in python

Do you want to know the details about “how to sort a dictionary by value in python”. If yes, you’re in the correct tutorial.

how to sort a dictionary by value in python

x = 1: 2, 3: 4, 4: 3, 2: 1, 0: 0

sort_by_key = dict(sorted(x.items(),key=lambda item:item[0]))
sort_by_value = dict(sorted(x.items(), key=lambda item: item[1]))

print("sort_by_key:", sort_by_key)
print("sort_by_value:", sort_by_value)

# sort_by_key: 0: 0, 1: 2, 2: 1, 3: 4, 4: 3
# sort_by_value: 0: 0, 2: 1, 1: 2, 4: 3, 3: 4
s = 1: 1, 7: 2, 4: 2, 3: 1, 8: 1
k = dict(sorted(s.items(),key=lambda x:x[0],reverse = True))
print(k)
newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 
import operator
x = 1: 2, 3: 4, 4: 3, 2: 1, 0: 0
sorted_x = sorted(x.items(), key=operator.itemgetter(1))


# Sort by key
import operator
x = 1: 2, 3: 4, 4: 3, 2: 1, 0: 0
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
d = 'one':1,'three':3,'five':5,'two':2,'four':4

# Sort
a = sorted(d.items(), key=lambda x: x[1])

# Reverse sort
r = sorted(d.items(), key=lambda x: x[1], reverse=True)
>>> x = 1: 2, 3: 4, 4: 3, 2: 1, 0: 0
>>> k: v for k, v in sorted(x.items(), key=lambda item: item[1])
0: 0, 2: 1, 1: 2, 4: 3, 3: 4

Final Thoughts

I hope this article helps you to know about “how to sort a dictionary by value in python”. If you have any doubts regarding this article please let us know via the comment section. Share this article with your friends and family via social networks.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coder Diksha. Here, I post about programming to help developers.

Share on:

Leave a Comment