GGFERCAS13
GGFERCAS13

Reputation: 13

filtering a dictionary in python

This is my code:

import csv
import os

filename = "StudentsPerformance.csv"
file = open(filename, "r", encoding="utf-8")
contents = csv.reader(file)


students = []
column_names = next(contents)
for row in contents:
    student = {
        "gender": row[0],
        "race/ethnicity": row[1],
        "parental level of education": row[2],
        "lunch": row[3],
        "test preparation course": row[4],
        "math score": row[5],
        "reading score": row[6],
        "writing score": row[7],
    }
    students.append(student)




def math_scores(student):
    return int(student["math score"])


def average_math_scores(student):
    scores = list(map(math_scores, students))
    total_scores = sum(scores)
    number_of_scores = len(scores)
    average_scores = total_scores / number_of_scores
    print(average_scores)
    return average_scores



if __name__ == '__main__':
    average_math_scores(students)

how can I make a filter so that male and female gets their own dict. So that I have a dict call female with all of their data and same for male. I have already defined the two dicts called female and male.

Upvotes: 1

Views: 1197

Answers (3)

Garrett Hyde
Garrett Hyde

Reputation: 5617

You can use List Comprehension to filter out each list.

males = [s for s in students if s['gender'] == 'male']
females = [s for s in students if s['gender'] == 'female']

You can also use the filter() function.

males = filter(lambda x: x['gender'] == 'male', students)
females = filter(lambda x: x['gender'] == 'female', students)

NOTE: filter() returns an iterator, not a list.

Reference

Upvotes: 2

angelogro
angelogro

Reputation: 124

Using python3

I assume this is your data, the code should work for more fields as well:

students=[{"gender":'m',"math_score":'A'},
          {"gender":'f',"math_score":'B'},
          {"gender":'m',"math_score":'D'},
          {"gender":'f',"math_score":'C'}]

You can use built-in filter function:

males=list(filter(lambda x:x["gender"]=='m',students))
females=list(filter(lambda x:x["gender"]=='f',students))

See documentation of filter function.

Upvotes: 5

Anis R.
Anis R.

Reputation: 6922

A list comprehension can come in handy here:

males = [x for x in students if x["gender"] == "male"]
females = [x for x in students if x["gender"] == "female"]

Upvotes: 0

Related Questions