sort the dictionary in python by R4R Team

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

Example-

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


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 keys of dictionary
x=OrderedDict(sorted(d.items(), key=lambda t: t[0]))
print("After sort by key, dictionary is")
print(x)


output-

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


-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!