在Python3中如何计算字典中特定值的倍数

2024-10-03 13:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道必须有一个非常简单的解决方案来解决这个问题,但我是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'}

非常感谢任何帮助!在


Tags: nameage解决方案genderpeople次数maledavid
3条回答

我建议重构一下你的逻辑,使用一个dicts列表。在

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'
    }
]

然后你可以用逻辑

^{pr2}$

这会给你名单上所有的男性

例如,您有申请者及其数据。您正在检查的数据是他们的性别,所以下面的代码将实现这一点。在

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

然后可以按如下方式使用:

^{pr2}$

相关问题 更多 >