Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two dicts by same key [duplicate]

Tags:

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?

like image 280
Ric S Avatar asked Jan 09 '19 11:01

Ric S


People also ask

How do I merge a list of Dicts into a single dict?

To merge multiple dictionaries, the most Pythonic way is to use dictionary comprehension {k:v for x in l for k,v in x. items()} to first iterate over all dictionaries in the list l and then iterate over all (key, value) pairs in each dictionary.

Can a dictionary have two key-value pairs with the same key?

No, each key in a dictionary should be unique. You can't have two keys with the same value.


1 Answers

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]} 
like image 102
yatu Avatar answered Sep 28 '22 20:09

yatu