1l = {1: 40, 2: 60, 3: 50, 4: 30, 5: 20}
2d1 = dict(sorted(l.items(),key=lambda x:x[1],reverse=True))
3print(d1) #output : {2: 60, 3: 50, 1: 40, 4: 30, 5: 20}
4d2 = dict(sorted(l.items(),key=lambda x:x[1],reverse=False))
5print(d2) #output : {5: 20, 4: 30, 1: 40, 3: 50, 2: 60}
1A={1:2, -1:4, 4:-20}
2{k:A[k] for k in sorted(A)}
3
4output:
5{-1: 4, 1: 2, 4: -20}
1from operator import itemgetter
2new_dict = sorted(data.items(), key=itemgetter(1))
1#for dictionary d
2sorted(d.items(), key=lambda x: x[1]) #for inceasing order
3sorted(d.items(), key=lambda x: x[1], reverse=True) # for decreasing order
4#it will return list of key value pair tuples
1In [1]: import collections
2
3In [2]: d = {2:3, 1:89, 4:5, 3:0}
4
5In [3]: od = collections.OrderedDict(sorted(d.items()))
6
7In [4]: od
8Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
1dictionary_items = a_dictionary.items()
2sorted_items = sorted(dictionary_items)