Element-wise addition of lists nested in two dictionaries (Python)

53 views Asked by At

I have two dictionaries, and the value for every key is a list of two elements, something like this:

dict1 = {1234: [40.26, 4.87], 13564 [30.24, 41.74], 523545 [810.13, 237.94]}
dict2 = {1231: [43.26, 8.87], 13564 [904.71, 51.81], 52234 [811.13, 327.35]}

I would like to get something like this:

dict3 = {1234: [40.26, 4.87], 1231: [43.26, 8.87], 13564 [934.95, 93.55], 523545 [810.13, 237.94], 52234 [811.13, 327.35]}

So far I have tried many things, but no luck. Does anybody know the answer for this element-wise addition?

1

There are 1 answers

2
Barmar On

Copy one of the dictionaries to the result. Then loop through the other dictionary, creating or adding to the corresponding key in the result.

from copy import deepcopy

dict3 = deepcopy(dict1)
for key, value in dict2.items():
    if key in dict3:
        dict3[key] = [value[0] + dict3[key][0], value[1] + dict3[key][1]]
    else:
        dict3[key] = value.copy()