Here, I use a nested comprehension to achieve what you want. First, I take corresponding items in d1
and d2
using zip()
. Then, I concatenate their keys, making that the key of the new dict, and use a list comprehension to sum the elements of their respective lists, which gets set as the value in the new dict.
d3 = {
i1[0] + i2[0]: [v1 + v2 for v1,v2 in zip(i1[1], i2[1])]
for i1,i2 in zip(d1.items(), d2.items())
}
# {'ad': [400, 800, 268], 'be': [500, 598, 279], 'cf': [750, 1067, 534]}
Note that, before Python 3.7, the 'order' of a dict was arbitrary. Now, when you call .items()
, you'll get keys in the order they were most recently added or defined, but before that you could get them in any order, and so the above would not work.