1x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
2
3sort_by_key = dict(sorted(x.items(),key=lambda item:item[0]))
4sort_by_value = dict(sorted(x.items(), key=lambda item: item[1]))
5
6print("sort_by_key:", sort_by_key)
7print("sort_by_value:", sort_by_value)
8
9# sort_by_key: {0: 0, 1: 2, 2: 1, 3: 4, 4: 3}
10# sort_by_value: {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
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
1d = {'one':1,'three':3,'five':5,'two':2,'four':4}
2
3# Sort
4a = sorted(d.items(), key=lambda x: x[1])
5
6# Reverse sort
7r = sorted(d.items(), key=lambda x: x[1], reverse=True)
1>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
2>>> for k in sorted(d, key=d.get, reverse=True):
3... k, d[k]
4...
5('bb', 4)
6('aa', 3)
7('cc', 2)
8('dd', 1)
1x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
2sorted_dict = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
3print(sorted_dict)
4#{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}