1

I have two dictionaries

first_dict = {2020: [1000, 50], 2021: [2000, 10], 2024: [500, 5]}
second_dict = {2019: [500, 20], 2020: [2000, 30], 2021: [1000, 10]}

How would I sum the first values and second values where they have the same key. To produce:

resulting_dict = {2019: [500, 20], 2020: [3000, 80], 2021: [3000, 20], 2024: [500, 5]}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Arlowest
  • 55
  • 5

1 Answers1

2

If you are certain that all lists are of length 2, you can use this:

first_dict = {2020: [1000, 50], 2021: [2000, 10], 2024: [500, 5]}
second_dict = {2019: [500, 20], 2020: [2000, 30], 2021: [1000, 10]}

keys = set(first_dict).union(second_dict)    
res = {k: list(map(sum, zip(first_dict.get(k, [0, 0]), second_dict.get(k, [0, 0])))) for k in keys}
print(res)  # -> {2019: [500, 20], 2020: [3000, 80], 2021: [3000, 20], 2024: [500, 5]}

If the length of the values-lists can vary, I would use zip_longest from itertools:

res = {k: list(map(sum, zip_longest(first_dict.get(k, [0]), 
                                    second_dict.get(k, [0]), 
                                    fillvalue=0))) for k in keys}
Ma0
  • 15,057
  • 4
  • 35
  • 65