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.
Try this:
d = defaultdict(int)
for model in models:
getids = model.objects.values_list('keyword', 'score')
for kw, score in getids:
d[kw] += score
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With