Blabber Blabber - 1 year ago 102
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},

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
, not checking if the
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},

Answer Source
[{'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}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download