python - 如何合并字典,从匹配的键中收集值?

标签 python dictionary merge

我有多个这样的字典(或键值对序列):

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/

相关文章:

python - 如果使用很长的字符串作为键,在 Dict 中搜索的时间复杂度是多少?

swift - 快速调用复杂字典(关联数组)上的过滤器

algorithm - 合并 K 个排序链表,为什么复杂度是 O(N * K * K),而不是 O(N * K)

SVN 建议我也合并自己合并的修订版

python - Django 3.1 |管理员页面外观问题

python - 使用 Python 进行 zappa 调度

python - 为什么 conda 不升级 Windows 上的某些软件包

python - 在 Python 中除大数

Kotlin elvis 运算符不适用于 map.get()

java - 在两个方向上合并两个列表