【问题标题】:Python Concatenate N dictionaries with highest values for each keyPython连接每个键的最高值的N个字典
【发布时间】:2013-05-26 08:25:51
【问题描述】:

我想从字典中创建一个新字典。

  • 所有字典中的所有键都必须出现在结果字典中
  • 所有键只能出现一次
  • 键的值是字典中所有值中的最大值

例如。

d1 = {'a':1, 'b':3}
d2 = {'a':5, 'd':5}
d3 = {'c':2, 'f':1}

d = {'a':5, 'b':3, 'c':2, 'd':5, 'f':1} 

另外,我希望对键(即字符串)进行排序,就像在我的示例中一样。我尝试使用update。但是,它正在用最新值覆盖现有值,而不是最高值。

【问题讨论】:

    标签: python dictionary concatenation


    【解决方案1】:
    >>> from collections import Counter
    >>> d1 = {'a':1, 'b':3}
    >>> d2 = {'a':5, 'd':5}
    >>> d3 = {'c':2, 'f':1}
    >>> Counter(d1) | Counter(d2) | Counter(d3)
    Counter({'a': 5, 'd': 5, 'b': 3, 'c': 2, 'f': 1})
    

    这使用multisetscollections.Counter 的并集

    如果您需要对结果进行排序:

    >>> from collections import Counter, OrderedDict
    >>> OrderedDict(sorted((Counter(d1) | Counter(d2) | Counter(d3)).items()))
    OrderedDict([('a', 5), ('b', 3), ('c', 2), ('d', 5), ('f', 1)])
    

    这可以通过使用reduce推广到N个字典

    >>> from functools import reduce
    >>> from operator import or_
    >>> reduce(or_, map(Counter, (d1, d2, d3)))
    Counter({'a': 5, 'd': 5, 'b': 3, 'c': 2, 'f': 1})
    

    【讨论】:

    • 这是一个非常密集的单线。
    • @Blender 现在我改用Counter 并删除了其他答案
    猜你喜欢
    • 2017-03-16
    • 2021-09-13
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2022-11-26
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多