【问题标题】:Returning largest dictionary sum from list of dictionaries从字典列表中返回最大的字典总和
【发布时间】:2017-01-06 21:29:59
【问题描述】:

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

>>>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],它会告诉我列表中的哪些项目具有最大值,但我不知道如何返回列表。我正在使用 Python 2.7 fwiw。

【问题讨论】:

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

标签: python python-2.7 list dictionary


【解决方案1】:

您可以简单地将max 与参数化的key 一起使用:

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

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

使用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}

【讨论】:

    【解决方案2】:

    您也可以通过使用带有嵌套dict理解表达式的max()来实现它:

    #         assuming the keys in all the sub-lists are same  v
    >>> {key: max(d[key] for d in testing) for key in testing[0].keys()}
    {'key3': 222, 'key2': 222, 'key1': 222}
    

    【讨论】:

    • 据我所知,这并不能回答问题。我认为 OP 不是在寻找最大 每个键,他/她正在寻找给定列表中具有最大 元素总和的 元素 /i>。虽然有点不清楚。
    猜你喜欢
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2021-01-31
    • 2020-09-15
    • 2023-01-11
    • 2021-06-17
    相关资源
    最近更新 更多