Python中字典列表上的条件操作

时间:2018-01-21 22:35:02

标签: python json list dictionary

我想根据另一个键的条件(例如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}
]

以下代码完成了它,但我想知道是否有更多的Pythonic / compact方法可以做到这一点?也许类似于词典列表的SQL查询?

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

1 个答案:

答案 0 :(得分:3)

这是怎么回事?

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

在技术上,您在生成器表达式上调用sum - 可以过滤到Gender等于“男性”的字典。

PEP 289为进一步阅读提供了一个示例。

要查找产品而不是总和:

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

如果你想在Python的标准库中找到产品:

from functools import reduce
from operator import mul
reduce(mul, (d['Age'] for d in list_of_dicts if d['Gender'] == 'male'), 1)