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}
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
1x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
2{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
3{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
1from collections import OrderedDict
2dd = OrderedDict(sorted(d.items(), key=lambda x: x[1]))
3print(dd)
1orders = {
2 'Pizza': 33,
3 'Burger': 45,
4 'Sandwich': 67,
5 'Latte': 39,
6 'Snickers': 48
7}
8
9sort_orders = sorted(orders.items(), key=lambda x: x[1], reverse=True)
10
11for i in sort_orders:
12 print(i[0], i[1])