How can I cumulatively sum defaultdict with same parameter? (Python)

Question:

I recently started using defaultdict in python.

When ım using defaultdict ı struggled to cumulative sum with same parameter.

In my case ı have defaultdict like that:

defaultdict(<class 'list'>,
        {'11106000022': [(216.0, datetime.datetime(2022, 10, 5, 0, 0)),
                         (216.0, datetime.datetime(2022, 10, 5, 0, 0)),
                         (370.0, datetime.datetime(2022, 10, 6, 0, 0)),
                         (110.0, datetime.datetime(2022, 10, 6, 0, 0))],
         '11106000053': [(89.0, datetime.datetime(2022, 10, 5, 0, 0)),
                         (500.0, datetime.datetime(2022, 10, 7, 0, 0))],
         '11106000083': [(50.0, datetime.datetime(2022, 10, 15, 0, 0))],
         '11106000126': [(170.0, datetime.datetime(2022, 10, 14, 0, 0))]}

For example, I want to cumulatively sum the numbers that fall on the same date in the first key. Finally I want to do this for all defaultdict.

{'11106000022': [(432.0, datetime.datetime(2022, 10, 5, 0, 0)),
                 (370.0, datetime.datetime(2022, 10, 6, 0, 0)),
                 (110.0, datetime.datetime(2022, 10, 6, 0, 0))]}

So in this output the value 216 is now 432 (same datetime).
Is there a way to solve this problem using map or dict comprehension . Or maybe something else.

Asked By: Tugrul Gokce

||

Answers:

data = defaultdict(...)
for key, val in data.items():
    sums_by_date = defaultdict(float)
    for item in val:
        sums_by_date[item[1]] += item[0]
    data[key] = [(v, k) for k, v in sums_by_date.items()]

which results in

{'11106000022': [(432.0, datetime.datetime(2022, 10, 5, 0, 0)), (480.0, datetime.datetime(2022, 10, 6, 0, 0))], 
'11106000053': [(89.0, datetime.datetime(2022, 10, 5, 0, 0)), (500.0, datetime.datetime(2022, 10, 7, 0, 0))], 
'11106000083': [(50.0, datetime.datetime(2022, 10, 15, 0, 0))], 
'11106000126': [(170.0, datetime.datetime(2022, 10, 14, 0, 0))]}

Could probably try to condense some of the above into fancy, more obscure comprehensions also.

Answered By: ccchoy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.