I'd like to sum the ages of all people in this list of dictionaries, based on a condition on another key (e.g. Gender == 'male'
):
list_of_dicts= [
{"Name": "Ethan", "Gender": "male", "Age": 11},
{"Name": "Nathan", "Gender": "male", "Age": 6},
{"Name": "Sophie", "Gender": "female", "Age": 14},
{"Name": "Patrick", "Gender": "male", "Age": 11}
]
The following code accomplishes it, but I wonder if there is a more Pythonic/compact way to do it? Maybe something like an SQL query for list of dictionaries?
total_male_age = 0
for dict in list_of_dicts:
if dict.get("Gender") == "male":
total_male_age = total_male_age + dict.get("Age")
#total_male_age = 28