给定一个字典列表,如何返回总和最大的字典
>>>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/