How to iterate through a list of class objects and total up how many attributes are the same?

Question:

I know the title is worded weird, I can’t think of how to best word this.

Basically I have to create a survey in python with an option to view statistics of all of the submissions. I’m storing the submissions as objects in a list.

One of the questions in the survey are radio buttons to choose your ethnicity, and I want to total up how many of each ethnicity there is.

I did get it to work using this:

    totalSubmissions = 0
    totalWhite = 0
    totalBlack = 0
    totalAsian = 0
    totalMixed = 0
    totalOther = 0
    for s in submissions:
        submissionList.insert(END, s.getInfo())
        totalSubmissions += 1
        if s.ethnicity == "White":
            totalWhite += 1
        elif s.ethnicity == "Black":
            totalBlack += 1
        elif s.ethnicity == "Asian":
            totalAsian += 1
        elif s.ethnicity == "Mixed":
            totalMixed += 1
        elif s.ethnicity == "Other":
            totalOther += 1

But this feels really inefficient and I’m sure there must be a better way to do this using iteration or something.

Asked By: Whendry123

||

Answers:

What is SubmissionList? their is no function in for it. Relook at your code. There are many variables not defined.

Answered By: Cruton246

I assume that you have a survey class as below

class Survey:
    def __init__(self, *args, **kwargs):
        # other attrs ..
        self.ethnicity = kwargs.get("ethnicity")

and then there is a list of submissions objects for example

submission_list = [
    Survey(ethnicity="White"),
    Survey(ethnicity="Black"),
    Survey(ethnicity="Asian"),
    Survey(ethnicity="Mixed"),
    Survey(ethnicity="Other"),
    Survey(ethnicity="White"),
    Survey(ethnicity="White"),
    Survey(ethnicity="Other"),
]

Now, you can get the total submission count as

total_submission = len(submission_list)
print("total_submission: ", total_submission)

And then define a dict for count of specific ethnicity, loop through the submissions list and check increase the ethnicity of the matched dict key.

total_dict = {
    "White": 0,
    "Black": 0,
    "Asian": 0,
    "Mixed": 0,
    "Other": 0,
}

for s in submission_list:
    total_dict[s.ethnicity] += 1

print("total_dict: ", total_dict)

Answered By: Ali Aref
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.