python - 从字典列表中返回最大的字典和

标签 python python-2.7 list dictionary

给定一个字典列表,如何返回总和最大的字典

>>>testing
[{'key1': 1, 'key2': 14, 'key3': 47},
 {'key1': 222, 'key2': 222, 'key3': 222},
  {'key1': 0, 'key2': 0, 'key3': 0}]

我想回去

{'key1': 222, 'key2': 222, 'key3': 222}

到目前为止,我已经尝试了 [sum(i.itervalues()) for i in testing] 这会告诉我列表中的哪些项目具有最大的值(value),但我不知道如何返回列表。我正在使用 Python 2.7 fwiw。

最佳答案

您可以简单地使用 max 参数化 key :

result = max(testing,key=lambda x : sum(x.itervalues()))

max(..)key返回给定 iterable 的最大值根据给定key功能。

python 运行这个给出:

$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> testing = [{'key1': 1, 'key2': 14, 'key3': 47},{'key1': 222, 'key2': 222, 'key3': 222},{'key1': 0, 'key2': 0, 'key3': 0}]
>>> max(testing,key=lambda x : sum(x.itervalues()))
{'key3': 222, 'key2': 222, 'key1': 222}

关于python - 从字典列表中返回最大的字典和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41514657/

相关文章:

python - 使用生成器发送方法。仍在尝试理解发送方法和古怪的行为

python - 查找pip包: pkg_resources specify custom target directory

html - 添加列表时 Logo 移出菜单

python - Blas GEMV 发射失败 : m=3, n=2 [Op:MatMul]

python - 将图像中颜色的不同深浅转换为一种颜色

python - 按变量分组、排序和打印来自另一列的值

Python,使用列表中的列表,还是列表中的对象?

python - 正则表达式删除字符串python中的单词

Python和环境变量

python - 优化暴力破解方法获得无重复字符的最长子串