user11631308
user11631308

Reputation:

Finding the sum of values in a list of objects matching certain parameters

I have a list of objects in the form {name: string, votes: int}. I want to iterate through my list and return the sum of votes for each object with a matching name.

So the data set

list = [{name: "Alpha", votes: 2}, {name: "Beta", votes: 5}, {name:"Alpha", votes:4}]

would return a new list

list2 = [{name: "Alpha" votes: 6}, {name: "Beta", votes: 5}]

I am running a for loop

for obj in list:
   list2.append(obj2(obj.name, sum(obj.votes))

I can't quite get the sum function to run. What I really want to say is find the sum of obj.votes where obj.name = something.

I also don't know what the names will be so I don't want to hard code anything here.

Upvotes: 0

Views: 329

Answers (3)

simonsanvil
simonsanvil

Reputation: 73

I would use list/set comprehension

unique_names = {d['name'] for d in lis}
[{'name':name, 'votes':sum([dic['votes'] for dic in lis if dic['name']==name])} for name  in unique_names]

You should also never use 'list' as a variable name as it is also a reserved python function.

Upvotes: 0

Prune
Prune

Reputation: 77850

Your posted code iterates through the list of three dicts, summing the votes for that individual dict. Summing an individual integer is silly.

You say that you want to sum all the votes for each name. If so, then you need to iterate through the names. For each name, find all dicts with that name, and sum those votes.

  1. Make a list of all unique names within your list of dicts.
  2. Write a loop to iterate through those names
  3. For any given name, make a list of vote values, extracting from each dict with that name
  4. Sum those votes

There's some pseudo-code. Each of these steps is a straightforward look-up, so I'll leave the detailed coding to you. :-)

Upvotes: 1

orlp
orlp

Reputation: 117771

This should do what you want:

from collections import defaultdict

def aggregate_votes(votelist):
    result = defaultdict(int)
    for bulkvote in votelist:
       result[bulkvote["name"]] += bulkvote["votes"]
    return dict(result)

Usage:

>>> li = [{"name": "Alpha", "votes": 2}, {"name": "Beta", "votes": 5},
...       {"name":"Alpha", "votes":4}]
>>> aggregate_votes(li)
{'Alpha': 6, 'Beta': 5}

Upvotes: 1

Related Questions