1s = {1: 1, 7: 2, 4: 2, 3: 1, 8: 1}
2k = dict(sorted(s.items(),key=lambda x:x[0],reverse = True))
3print(k)
1import operator
2x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
3sorted_x = sorted(x.items(), key=operator.itemgetter(1))
4
5
6# Sort by key
7import operator
8x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
9sorted_x = sorted(x.items(), key=operator.itemgetter(0))
10
1unsorted_list = [{"key1":5, "key2":2}, {"key1":5, "key2":1}]
2sorted_list = sorted(unsorted_list, key=lambda k: k["key2"])
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}
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}