3

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
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
sc28
  • 1,163
  • 4
  • 26
  • 48

1 Answers1

5

How's this?

>>> sum(d['Age'] for d in list_of_dicts if d['Gender'] == 'male')
28

Here you are technically calling sum on a generator expression--one that filters down to dictionaries where Gender equals "male".

PEP 289 provides an example for some further reading.

To find a product rather than a sum:

import numpy as np
np.product([d['Age'] for d in list_of_dicts if d['Gender'] == 'male'])

And if you want to find a product while staying within Python's standard library:

from functools import reduce
from operator import mul
reduce(mul, (d['Age'] for d in list_of_dicts if d['Gender'] == 'male'), 1)
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235