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?
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.
No, each key in a dictionary should be unique. You can't have two keys with the same value.
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]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With