[英]How to count how many times a specific value in a dictionary of dictionaries in Python 3
我知道这个问题必须有一个非常简单的解决方案,但我是 Python 新手,无法弄清楚如何去做。
我只想做的是计算特定值在这本字典中出现的次数,例如,有多少个男性。
people = {}
people['Applicant1'] = {'Name': 'David Brown',
'Gender': 'Male',
'Occupation': 'Office Manager',
'Age': '33'}
people['Applicant2'] = {'Name': 'Peter Parker',
'Gender': 'Male',
'Occupation': 'Postman',
'Age': '25'}
people['Applicant3'] = {'Name': 'Patricia M',
'Gender': 'Female',
'Occupation': 'Teacher',
'Age': '35'}
people['Applicant4'] = {'Name': 'Mark Smith',
'Gender': 'Male',
'Occupation': 'Unemployed',
'Age': '26'}
任何帮助深表感谢!
对于您的示例,您有申请人及其数据。 您正在检查的数据是他们的性别,因此下面的代码将实现这一点。
amount = 0 # amount of people matching condition
for applicant in people.values(): # looping through all applicants
if applicant.get('Gender', False) == 'Male': # checks if applicant['Gender'] is 'Male'
# note it will return False if ['Gender'] wasn't set
amount += 1 # adds matching people to amount
这将获得申请人列表中的男性数量。
这是一个计算字典中给定值出现次数的函数:
def count(dic, val):
sum = 0
for key,value in dic.items():
if value == val:
sum += 1
if type(value) is dict:
sum += count(dic[key], val)
return sum
然后您可以按如下方式使用它:
result = count(people, 'Male')
我建议稍微重构您的逻辑以使用字典列表。
people = [
{
'Name': 'David Brown',
'Gender': 'Male',
'Occupation': 'Office Manager',
'Age': '33'
},
{
'Name': 'Peter Parker',
'Gender': 'Male',
'Occupation': 'Postman',
'Age': '25'
},
{
'Name': 'Patricia M',
'Gender': 'Female',
'Occupation': 'Teacher',
'Age': '35'
},
{
'Name': 'Mark Smith',
'Gender': 'Male',
'Occupation': 'Unemployed',
'Age': '26'
}
]
然后你可以使用类似的逻辑
[applicant for applicant in people if applicant['Gender'] == 'Male']
这将为您提供列表中的所有男性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.