0

After scraping a web table, I stored all the values for each row as a dictionary and then appending all the dictionaries in a list. In doing so, I get below dictionaries (sample) which can have the same key-value pairs, Eg: store 123 & 789 are present in 2 dictionaries:

${data} = [{store: 123, prov: 'ON' value: 10},{store: 456, prov: 'AB' value: 5},{store: 123, prov: 'ON' value: 4},{store: 789, prov: 'MB' value: 3},{store: 789, prov: 'MB' value: 7}]

How can i merge and sum value of all these dictionary items in order to get only unique elements like:

${data} = [{store: 123, prov: 'ON' value: 14},{store: 456, prov: 'AB' value: 5},{store: 789, prov: 'MB' value: 10}]

The solution can be provided using python as well.

Note: I found some python solutions but they only work when each dictionary is stored as a separate variable Merge and sum of two dictionaries

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Hemendra
  • 81
  • 8
  • Answers in this post should help you out: [https://stackoverflow.com/questions/62102618/sum-values-in-a-list-of-lists-of-dictionaries-using-common-key-value-pairs](https://stackoverflow.com/questions/62102618/sum-values-in-a-list-of-lists-of-dictionaries-using-common-key-value-pairs) – Ank May 18 '21 at 06:24
  • Does this answer your question? [Sum values in a list of lists of dictionaries using common key-value pairs](https://stackoverflow.com/questions/62102618/sum-values-in-a-list-of-lists-of-dictionaries-using-common-key-value-pairs) – Todor Minakov May 18 '21 at 06:31

1 Answers1

0

Do you mean you don't want to store in a new dictionary and print like this?

data = [{'store': 123, 'value': 10},{'store': 456, 'value': 5},{'store': 123, 'value': 
4},{'store': 789, 'value': 3},{'store': 789, 'value': 7}]

Dict = {}
for x in data:
        if x['store'] in Dict:
                Dict[x['store']] += x['value']
        else:
                Dict[x['store']] = x['value']
     
print([{'store':x,'value':y} for x,y in Dict.items()])
angel_dust
  • 121
  • 2
  • 10
  • Thanks @osamu-zenji for the answer. I have slightly modified the `data` values and added extra key-value pair `prov` which i forgot to mention earlier. I would like to store the data in a new list of dictionaries instead of the solution provided by you. **Note**: if there are matching stores, only the `value` will change, other key-values pairs will remain same. – Hemendra May 18 '21 at 10:29