Merge two dicts by same key

  • A+
Category:Languages

I have the following two toy dicts

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.

I tried the following code

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]]} 

whereas I would like to obtain

{'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]} 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: