Blabber Blabber - 4 months ago 11
Python Question

Python sum values of list of dictionaries if two other key value pairs match

I have a list of dictionaries of the following form:

lst = [{"Name":'Nick','Hour':0,'Value':2.75},
{"Name":'Sam','Hour':1,'Value':7.0},
{"Name":'Nick','Hour':0,'Value':2.21},
{'Name':'Val',"Hour":1,'Value':10.1},
{'Name':'Nick','Hour':1,'Value':2.1},
{'Name':'Val',"Hour":1,'Value':11},]


I want to be able to sum all values for a name for a particular hour, e.g. if
Name == Nick and Hour == 0
, I want value to give me the sum of all values meeting the condition.
2.75 + 2.21
, according to the piece above.

I have already tried the following but it doesn't help me out with both conditions.

finalList = collections.defaultdict(float)
for info in lst:
finalList[info['Name']] += info['Value']
finalList = [{'Name': c, 'Value': finalList[c]} for c in finalList]


This sums up all the values for a particular
Name
, not checking if the
Hour
was the same. How can I incorporate that condition into my code as well?

My expected output :

finalList = [{"Name":'Nick','Hour':0,'Value':4.96},
{"Name":'Sam','Hour':1,'Value':7.0},
{'Name':'Val',"Hour":1,'Value':21.1},
{'Name':'Nick','Hour':1,'Value':2.1}...]

Answer
[{'Name':name, 'Hour':hour, 'Value': sum(d['Value'] for d in lst if d['Name']==name and d['Hour']==hour)} for hour in hours for name in names]

if you don't already have all names and hours in lists (or sets) you can get them like so:

names = {d['Name'] for d in lst}
hours= {d['Hour'] for d in lst}