python - 合并字典,保留重复键的值

标签 python merge duplicates

给定 n 个字典,编写一个函数,该函数将返回一个唯一字典,其中包含重复键的值列表。

例子:

d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'b': 4}
d3 = {'a': 5, 'd': 6}

结果:
>>> newdict
{'c': 3, 'd': 6, 'a': [1, 5], 'b': [2, 4]}

到目前为止我的代码:
>>> def merge_dicts(*dicts):
...     x = []
...     for item in dicts:
...         x.append(item)
...     return x
...
>>> merge_dicts(d1, d2, d3)
[{'a': 1, 'b': 2}, {'c': 3, 'b': 4}, {'a': 5, 'd': 6}]

生成一个为这些重复键生成一个值列表的新字典的最佳方法是什么?

最佳答案

Python 提供了一个简单而快速的解决方案: defaultdict collections模块。从文档中的示例:

Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists:

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items() [('blue', [2, 4]), ('red', 1), ('yellow', [1, 3])]

When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list.



在您的情况下,大致是:
import collections

def merge_dicts(*dicts):
    res = collections.defaultdict(list)
    for d in dicts:
        for k, v in d.iteritems():
            res[k].append(v)
    return res

>>> merge_dicts(d1, d2, d3)
defaultdict(<type 'list'>, {'a': [1, 5], 'c': [3], 'b': [2, 4], 'd': [6]})

关于python - 合并字典,保留重复键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24745181/

相关文章:

r - 计算重复R代码的出现次数

sql - 在 SQL Server 中删除带有联接的表

python - 使用 pyteserract 0.1.5 我在使用 print image_to_string(img) 后出现以下错误,它找不到什么文件?

python - 从具有相同字段名称的多个表单中获取所有值,无需表单集

r - 合并具有多个值的列

merge 后的 Git 分支和提交历史

pandas - 合并 Pandas 数据框 : how to add columns and replace values

MySQL 插入新行并忽略现有行,基于许多列

python - 如何从图像中分离出人脸?

python - 在 macOS 上编译时输入字段不可编辑 + 不稳定的箭头