Python程序按值的总和对字典列表进行排序
给定字典列表,按其值的总和排序。
Input : test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 100}, {8 : 9, 7 : 3}]
Output : [{8: 9, 7: 3}, {1: 3, 4: 5, 3: 5}, {1: 100}]
Explanation : 12 < 13 < 100, sorted by values sum.
Input : test_list = [{1 : 100}, {8 : 9, 7 : 3}]
Output : [{8: 9, 7: 3}, {1: 100}]
Explanation : 12 < 100, sorted by values sum.
方法 #1:使用sort() + sum() + values()
在这里,执行排序的任务是使用 sort() 完成的,而 sum() 和 values() 用于获取字典所有值的总和。
Python3
# Python3 code to demonstrate working of
# Sort Dictionaries by Values Sum
# Using sort() + sum() + values()
def values_sum(row):
# return values sum
return sum(list(row.values()))
# initializing list
test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 7, 10 : 1, 3 : 10}, {1 : 100}, {8 : 9, 7 : 3}]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
test_list.sort(key = values_sum)
# printing result
print("Sorted Dictionaries List : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Dictionaries by Values Sum
# Using sorted() + lambda + sum() + values()
# initializing list
test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 7, 10 : 1, 3 : 10}, {1 : 100}, {8 : 9, 7 : 3}]
# printing original list
print("The original list is : " + str(test_list))
# lambda function to get values sum
res = sorted(test_list, key = lambda row : sum(list(row.values())))
# printing result
print("Sorted Dictionaries List : " + str(res))
输出:
The original list is : [{1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}, {8: 9, 7: 3}]
Sorted Dictionaries List : [{8: 9, 7: 3}, {1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}]
方法 #2:使用sorted() + lambda + sum() + values()
在这里,我们使用 sorted() 执行排序并使用 lambda函数提供逻辑。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Dictionaries by Values Sum
# Using sorted() + lambda + sum() + values()
# initializing list
test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 7, 10 : 1, 3 : 10}, {1 : 100}, {8 : 9, 7 : 3}]
# printing original list
print("The original list is : " + str(test_list))
# lambda function to get values sum
res = sorted(test_list, key = lambda row : sum(list(row.values())))
# printing result
print("Sorted Dictionaries List : " + str(res))
输出:
The original list is : [{1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}, {8: 9, 7: 3}]
Sorted Dictionaries List : [{8: 9, 7: 3}, {1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}]