Sort the dictionary by values in python by R4R Team

-Here we try to sort the dictionary data according to the values.

Example-

dictionary is {'c':1,'a':4,'z':2}
then after sort dictionary become {'c':1,'z':2,'a':4}


program-

#import the OrderedDict from collections module
from collections import OrderedDict

#given unsorted dictionary
d={'b':3,'a':2,'c':4,'d':1}
print("Dictionary is:",d)

#sort according to values of dictionary
x=OrderedDict(sorted(d.items(), key=lambda t: t[1]))
print("After sort by values, dictionary is")
print(x)


output-

Dictionary is: {'b': 3, 'a': 2, 'c': 4, 'd': 1}
After sort by values, dictionary is
OrderedDict([('d', 1), ('a', 2), ('b', 3), ('c', 4)])


-In this program, we have a dictionary {'b':3,'a':2,'c':4,'d':1}, then we sort this dictionary with the use of lambda function.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!