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


i have list of dictionaries of 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 able sum values name particular hour, e.g. if name == nick , hour == 0, want value give me sum of values meeting condition. 2.75 + 2.21, according piece above.

i have tried following doesn't me out both conditions.

finallist = collections.defaultdict(float) info in lst:     finallist[info['name']] += info['value'] finallist = [{'name': c, 'value': finallist[c]} c in finallist]   

this sums values particular name, not checking if hour same. how can incorporate condition code 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}...]   

[{'name':name, 'hour':hour, 'value': sum(d['value'] d in lst if d['name']==name , d['hour']==hour)} hour in hours name in names] 

if don't have names , hours in lists (or sets) can them so:

names = {d['name'] d in lst} hours= {d['hour'] d in lst} 

Comments