Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python将N个字典与每个键的最大值连接起来_Python_Dictionary_Concatenation - Fatal编程技术网

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})