I have a list in which each value is a list of tuples. for example this is the value which I extract for a key :
[(\'1998-01-20\',8) , (\'1998-01-22\',4) ,
Try using itertools.groupby
to aggregate values by month:
from itertools import groupby
a = [('1998-01-20', 8), ('1998-01-22', 4), ('1998-06-18', 8),
('1999-07-15', 7), ('1999-07-21', 1)]
for key, group in groupby(a, key=lambda x: x[0][:7]):
print key, sum(j for i, j in group)
# Output
1998-01 12
1998-06 8
1999-07 8
Here's a one-liner version:
print [(key, sum(j for i, j in group)) for key, group in groupby(a, key=lambda x: x[0][:7])]
# Output
[('1998-01', 12), ('1998-06', 8), ('1999-07', 8)]