How can I merge two dict of list together and sum the values of duplicate

I have two python dictionaries which have been trying to merge and sum the values of keys that are the same.

I have tried using Counter but not getting it.

dict1 = {'carrot' : [2, 3, 4], 'cabbage' : [5,6,7], 'cucumber' : [8, 9, 10]}

dict2 = {'carrot' : [-1, 4, 5], 'raw rice' : [6, 7, 8]}

Expected result:

Merged_dict = {'carrot' : [1, 7, 9], 'cabbage' : [5, 6, 7],  'cucumber' : [8, 9, 10], 'raw rice' : [6, 7, 8]}

Thanks in anticipation

Hi,

  1. create a dictionary dict3 as follows:
    dict3 = {**dict1, **dict2}
  2. Now loop for key, value in dict3.items and find the same keys that are in dict1 and dict2 and zip the value of dict3 and dict1[key] and assign the result to dict3[key].

I have defined a function that returns dict3 and test it with your dict1 and dict2.
The result is exactly the same as your Merged_dict!

I have been trying implementing your solution but to no avail.
Can you show me if you don’t mind?

We have a strict “we won’t do your homework for you” policy on the forum. What code have you written so far? If you post that code, we can help you fix it.

So to rephrase it:
You are looking for a dictionairy where the values of all keys are the sum of the values in the array-indices in each dictionairy IF the key is both OR just the array else.

If you know how to adress key-value in a dict, this shouldn’t be to hard.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.