Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultdict how to get sum of all values in a list?

Tags:

python

Here is the code:

models = [Url1, Url2, Url3, Url4, Url5, Url6, Url7, Url8, Url9, Url10]
d = defaultdict(list)

for model in models:

    getids = model.objects.values_list('keyword', 'score')
    for kw, score in getids:
        d[kw].append(score)

This makes 'd' output this:

defaultdict(<type 'list'>, {198: [-70, 0, 5, -70, 5, 5, 0, 0, -50, -70],     
199: [0, -70, -70, -70, -70, -70, -100, -70, -70, -70]})

How to make it return this:

defaultdict({198: -245, 199: -660}) #sum of all numbers inside lists, returned as values to both keys.

I tried for looping but deafultdict doesn't seem to work like normal lists.

like image 388
Nema Ga Avatar asked Dec 06 '25 01:12

Nema Ga


2 Answers

Try this:

d = defaultdict(int)

for model in models:

    getids = model.objects.values_list('keyword', 'score')
    for kw, score in getids:
        d[kw] += score
like image 156
Linuxios Avatar answered Dec 08 '25 13:12

Linuxios


You can use dict comprehensive to take the sum of each values

 summed = {k: sum(v) for (k, v) in d.items()}
 print(summed) 
 >>> {198: -245, 199: -660}

Also, defaultdict acts like a dictionary, not as a list.

like image 28
Wondercricket Avatar answered Dec 08 '25 14:12

Wondercricket