-2

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?

  • Rough sketch: use `groupby` on `chain(dict1.items(), dist2.items())`, then use `functools.reduce` and `map(operator.add, ...)` to reduce the lists associated with each key to a single list. – chepner Feb 04 '23 at 21:37

1 Answers1

1

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()
Barmar
  • 741,623
  • 53
  • 500
  • 612