Python 程序按字典值的总和对字典列表进行排序
如果需要根据字典的值的总和对字典列表进行排序,那么定义一个方法,使用“sum”方法来确定结果。
以下是示例 −
示例
def sum_value(row):
return sum(list(row.values()))
my_dict = [{21 : 13, 44 : 35, 34 : 56}, {11 : 75, 70 : 19, 39 : 70}, {1 : 155}, {48 : 29, 17 : 53}]
print("The dictionary is :")
print(my_dict)
my_dict.sort(key = sum_value)
print("The result is :")
print(my_dict)输出
The dictionary is :
[{34: 56, 44: 35, 21: 13}, {11: 75, 70: 19, 39: 70}, {1: 155}, {48: 29, 17: 53}]
The result is :
[{48: 29, 17: 53}, {34: 56, 44: 35, 21: 13}, {1: 155}, {11: 75, 70: 19, 39: 70}]
说明
定义了一个名为“sum_value”的方法,该方法将行作为参数,并使用“.values”和“sum”方法返回行值之和。
定义了一个整数字典,并在控制台上显示。
对字典进行排序,并通过将键传递为之前定义的值来调用方法。
这是在控制台上显示的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP