Merge dictionaries retaining values for duplicate keys(合并字典,保留重复键的值)
问题描述
给定 n 个字典,编写一个函数,该函数将返回一个唯一字典,其中包含重复键的值列表.
Given n dictionaries, write a function that will return a unique dictionary with a list of values for duplicate keys.
例子:
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}]
生成一个为这些重复键生成一个值列表的新字典的最佳方法是什么?
What would be the best way to produce a new dictionary that yields a list of values for those duplicate keys?
推荐答案
def merge_dicts(*dicts):
    d = {}
    for dict in dicts:
        for key in dict:
            try:
                d[key].append(dict[key])
            except KeyError:
                d[key] = [dict[key]]
    return d
这会返回:
{'a': [1, 5], 'b': [2, 4], 'c': [3], 'd': [6]}
这个问题略有不同.这里所有的字典值都是列表.如果长度为 1 的列表不希望这样做,则添加:
There is a slight difference to the question. Here all dictionary values are lists. If that is not to be desired for lists of length 1, then add:
    for key in d:
        if len(d[key]) == 1:
            d[key] = d[key][0]
在 return d 语句之前.但是,我真的无法想象您何时想要删除该列表.(考虑将列表作为值的情况;然后删除项目周围的列表会导致模棱两可的情况.)
before the return d statement. However, I cannot really imagine when you would want to remove the list. (Consider the situation where you have lists as values; then removing the list around the items leads to ambiguous situations.)
这篇关于合并字典,保留重复键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:合并字典,保留重复键的值
				
        
 
            
        基础教程推荐
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 - Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 - 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 - 包装空间模型 2022-01-01
 - 求两个直方图的卷积 2022-01-01
 - PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				