Python - 按键值总和对字典进行排序
给定一个字典,按键和值的总和排序。
Input : test_dict = {3:5, 1:3, 4:6, 2:7, 8:1}
Output : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6}
Explanation : 4 < 8 < 9 = 9 < 10 are increasing summation of keys and values.
Input : test_dict = {3:5, 1:3, 4:6, 2:7}
Output : {1: 3, 3: 5, 2: 7, 4: 6}
Explanation : 4 < 8 < 9 < 10 are increasing summation of keys and values.
方法:使用 sorted() + lambda + items()
在此排序操作中使用sorted() 执行,使用 lambda函数提供加法逻辑。 items()用于获取键和值。
Python3
# Python3 code to demonstrate working of
# Sort Dictionary by key-value Summation
# Using sorted() + lambda + items()
# initializing dictionary
test_dict = {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorted() to sort, lambda provides key-value addition
res = sorted(test_dict.items(), key=lambda sub: sub[0] + sub[1])
# converting to dictionary
res = {sub[0]: sub[1] for sub in res}
# printing result
print("The sorted result : " + str(res))
输出:
The original dictionary is : {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
The sorted result : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6}