Reputation: 51
I have this list in Python:
L_initial=[[1,'2019-01-01'], [1,'2019-01-01'],[2,'2019-02-02'],[4,'2019-03-03'],[5,'2019-03-04']]
I want to sum up all first value of the elements, grouped by same month of time-stamp form string, a final list is like this:
L_final=[[2,'2019-01'],[2,'2019-02'],[9,'2019-03']]
I am able to do it by day but not by month, this is my code for sum day per day :
dico = {}
for v, k in liste_initial:
dico[k] = dico.get(k, 0) + v
liste_final=[[v, k] for k, v in dico.items()]
Upvotes: 3
Views: 64
Reputation: 147146
Since your dates are in YYYY-MM-DD
format, you can simply take the first 7 characters of each date to group by month:
liste_initial = [[1,'2019-01-01'], [1,'2019-01-01'],[2,'2019-02-02'],[4,'2019-03-03'],[5,'2019-03-04']]
dico = {}
for v, k in liste_initial:
dico[k[:7]] = dico.get(k[:7], 0) + v
liste_final=[[v, k] for k, v in dico.items()]
Output:
[[2, '2019-01'], [2, '2019-02'], [9, '2019-03']]
Upvotes: 2