Python将N个字典与每个键的最大值连接起来
我想从字典创建一个新的字典Python将N个字典与每个键的最大值连接起来,python,dictionary,concatenation,Python,Dictionary,Concatenation,我想从字典创建一个新的字典 所有字典中的所有键都必须出现在结果字典中 所有钥匙必须只存在一次 键的值是字典中所有值中的最高值 前 此外,我希望对键(即字符串)进行排序,如我的示例中所示。我尝试使用update。但是,它将用最新值而不是最高值覆盖现有值 >>> from collections import Counter >>> d1 = {'a':1, 'b':3} >>> d2 = {'a':5, 'd':5} >>>
- 所有字典中的所有键都必须出现在结果字典中
- 所有钥匙必须只存在一次
- 键的值是字典中所有值中的最高值
update
。但是,它将用最新值而不是最高值覆盖现有值
>>> 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})
这使用了通过
如果需要对结果进行排序:
>>> 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
>>> 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现在我改为使用
计数器,并删除了其他答案
>>> 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})