通过同一键合并两个字典 [英] Merge two dicts by same key
本文介绍了通过同一键合并两个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下两个玩具字典
d1 = {
'a': [2,4,5,6,8,10],
'b': [1,2,5,6,9,12],
'c': [0,4,5,8,10,21]
}
d2 = {
'a': [12,15],
'b': [14,16],
'c': [23,35]
}
我想得到一个唯一的字典,在该字典中,我将第二个字典值堆叠在第一个字典之后,并放在相同的方括号内.
and I would like get a unique dictionary where I stack the second dictionary values after the first ones, within the same square brackets.
我尝试了以下代码
d_comb = {key:[d1[key], d2[key]] for key in d1}
但是我获得的输出在每个键的列表中有两个列表,即
but the output I obtain has two lists within a list for each key, i.e.
{'a': [[2, 4, 5, 6, 8, 10], [12, 15]],
'b': [[1, 2, 5, 6, 9, 12], [14, 16]],
'c': [[0, 4, 5, 8, 10, 21], [23, 35]]}
我想获得
{'a': [2, 4, 5, 6, 8, 10, 12, 15],
'b': [1, 2, 5, 6, 9, 12, 14, 16],
'c': [0, 4, 5, 8, 10, 21, 23, 35]}
如何用一行或两行代码做到这一点?
How can I do that with a line or two of code?
推荐答案
您几乎拥有了它,而是使用+
附加了两个列表:
You almost had it, instead use +
to append both lists:
{key: d1[key] + d2[key] for key in d1}
{'a': [2, 4, 5, 6, 8, 10, 12, 15],
'b': [1, 2, 5, 6, 9, 12, 14, 16],
'c': [0, 4, 5, 8, 10, 21, 23, 35]}
这篇关于通过同一键合并两个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文