Python连接每个键具有最高值的N个词典

时间:2013-05-26 08:25:51

标签: python dictionary concatenation

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

  • 所有词典中的所有键必须出现在结果词典中
  • 所有密钥必须只出现一次
  • key的值是字典中所有值的最高值

离。

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。但是,它使用最新值而不是最高值覆盖现有值。

1 个答案:

答案 0 :(得分:5)

>>> 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})
相关问题