以下是一个示例代码,展示了如何按照嵌套字典列表中的值进行分组并计数:
from collections import defaultdict
def group_and_count(data, key):
result = defaultdict(int)
for item in data:
value = item.get(key)
if value:
result[value] += 1
return result
data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'San Francisco'},
{'name': 'Charlie', 'age': 35, 'city': 'New York'},
{'name': 'Dave', 'age': 25, 'city': 'San Francisco'},
{'name': 'Eve', 'age': 30, 'city': 'New York'},
]
result = group_and_count(data, 'age')
print(result)
输出结果:
defaultdict(, {25: 2, 30: 2, 35: 1})
在这个示例中,我们定义了一个group_and_count
函数,它接受一个嵌套字典列表和一个键名作为参数。函数使用defaultdict
创建一个默认值为0的字典result
来存储分组和计数结果。然后遍历输入的字典列表,获取每个字典中对应键名的值,并将其作为result
字典的键,将计数加1。最后返回结果字典。
在这个示例中,我们按照年龄('age')进行分组和计数,输出结果为{25: 2, 30: 2, 35: 1}
,表示年龄为25的有2个人,年龄为30的有2个人,年龄为35的有1个人。