How to sum elements in list of dictionaries if two key values are the same

  • A+
Category:Languages

I have the following list of dictionaries:

dictionary =[{'Flow': 100, 'Location': 'USA', 'Name': 'A1'},             {'Flow': 90, 'Location': 'Europe', 'Name': 'B1'},             {'Flow': 20, 'Location': 'USA', 'Name': 'A1'},             {'Flow': 70, 'Location': 'Europe', 'Name': 'B1'}] 

I want to create a new list of dictionaries, with summed Flow values of all dictionaries where Location and Name are the same. My desired output would be:

new_dictionary =[{'Flow': 120, 'Location': 'USA', 'Name': 'A1'},             {'Flow': 160, 'Location': 'Europe', 'Name': 'B1'},] 

How can I achieve this?

 


This is possible, but non-trivial to implement in python. Might I suggest using pandas? This is simple with a groupby, sum, and to_dict.

import pandas as pd  (pd.DataFrame(dictionary)    .groupby(['Location', 'Name'], as_index=False)    .Flow.sum()    .to_dict('r'))  [{'Flow': 160, 'Location': 'Europe', 'Name': 'B1'},  {'Flow': 120, 'Location': 'USA', 'Name': 'A1'}] 

To install, use pip install --user pandas.


Otherwise, you can apply a pseudo-generic group operation using itertools.groupby.

from itertools import groupby from operator import itemgetter  grouper = ['Location', 'Name'] key = itemgetter(*grouper) dictionary.sort(key=key)  [{**dict(zip(grouper, k)), **{'Flow': sum(map(itemgetter('Flow'), g))}}      for k, g in groupby(dictionary, key=key)]  [{'Flow': 160, 'Location': 'Europe', 'Name': 'B1'},  {'Flow': 120, 'Location': 'USA', 'Name': 'A1'}] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: