我有多个这样的字典(或键值对序列):
d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}
我怎样才能有效地得到这样的结果,作为一个新的字典?
d = {key1: (x1, x2), key2: (y1, y2)}
最佳答案
这是一个通用的解决方案,可以处理任意数量的字典,当键仅在一些字典中时:
from collections import defaultdict
d1 = {1: 2, 3: 4}
d2 = {1: 6, 3: 7}
dd = defaultdict(list)
for d in (d1, d2): # you can list as many input dicts as you want here
for key, value in d.items():
dd[key].append(value)
print(dd) # result: defaultdict(<type 'list'>, {1: [2, 6], 3: [4, 7]})
关于python - 如何合并字典,从匹配的键中收集值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5946236/