-2

How can I add multiple dictionaries in lists having name, value pairs such as:

dict1 = [{'name':'A','value':6}, {'name':'B', 'value':5}]

dict2 = [{'name':'A', 'value':10}, {'name':'C', 'value':12}]

Giving output as:

dict3 = [{'name':'A', 'value':16}, {'name':'B', 'value':5}, {'name':'C', 'value':12}]

Names in dictionary are not fixed and therefore random value in name field are possible.

glhr
  • 4,439
  • 1
  • 15
  • 26
Ashu Grover
  • 737
  • 1
  • 11
  • 26
  • [here](https://stackoverflow.com/questions/33931259/to-merge-two-dictionaries-of-list-in-python) is an example of how to merge two dictionaries into a list. – Pooya Panahandeh May 03 '19 at 07:53
  • note that you are using a list of dictionaries `[{}, {}, ..., {}]`, and not a plain dictionary `{}`. – bkupfer May 03 '19 at 07:59
  • you can try reading this post: https://stackoverflow.com/questions/33931259/to-merge-two-dictionaries-of-list-in-python – Victor Emil Simonsen May 03 '19 at 08:03
  • @VictorEmilSimonsen @jonrsharpe, @TimH This is not a duplicate, because it is not a straight key-value dict, the key is mapped by `name` field and value by `value` field. All the suggested links are very different. – Ashu Grover May 03 '19 at 08:39
  • 1
    This post is asking about how to merge *multiple* dicts. The dupe target asks about how to merge 2 dictionaries specifically, ie not answering this question. Voting to reopen. – zabop Nov 05 '21 at 08:20

3 Answers3

3

Try this if you want to sum all values for unique 'name' in each dictionaries :

names = set([k['name'] for k in dict1+dict2])
dict3 = []
for name in names:
    temp_val = []
    for dict_ in dict1+dict2:
        if dict_['name'] == name:
            temp_val.append(dict_['value'])
    dict3.append({'name': name, 'value' : sum(temp_val)})

OUTPUT :

[{'name': 'A', 'value': 16}, {'name': 'B', 'value': 5}, {'name': 'C', 'value': 12}]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
1

Using collections.defaultdict:

res = defaultdict(int)
for d in dict1+dict2:
    res[d['name']] += d['value']
[{'name': k, 'value':v} for k,v in res.items()]

Output:

[{'name': 'B', 'value': 5},
 {'name': 'C', 'value': 12},
 {'name': 'A', 'value': 16}]
Chris
  • 29,127
  • 3
  • 28
  • 51
0

What you have is a list of dictionaries with one key each, you can make that data structure much cleaner like so

dict1 = {'A' :6 , 'B' :5 }
dict2 = { 'A':10 , 'C' : 12 }

After that you can use Counter to simplify the addition

from collections import Counter

dict1 = {'A' :6 , 'B' :5 }
dict2 = { 'A':10 , 'C' : 12 }

#Add the two counters and get the result
dict3 = Counter(dict1) + Counter(dict2)
print(dict(dict3))

The output will be

{'A': 16, 'B': 5, 'C': 12}
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40