用python计算雇员字典数据库中的值

2024-04-19 03:50:20 发布

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

python对我来说是一门新语言,所以这个问题听起来可能很简单,但是如果有人能为我指出正确的方向,我会很感激的!我创建了一个叫员工的字典,里面有一些关于他们的价值:

我想知道每个部门有多少人,例如:科技2号,会计1号。在

我有这样的东西,但打印出来是空白的。在

  def main():
   employees= {'name': 'John', 'empID': '102', 'dpt': 'tech', 'title': 
   'programmer', 'salary': '75'}
   {'name': 'Jane', 'empID': '202', 'dpt': 'tech', 'title': 'programmer', 
   'salary': '80'}
   {'name': 'Joe', 'empID': '303', 'dpt': 'accounting', 'title': 
   'accountant', 'salary': '85'}
    for item in employees:
    dic = employees[item]
    if dic['dpt'[0]]==dic['dpt'[1]]:
        duplicate += 1
        print("there are "+ duplicate)
    else:
        print("There are no duplicate")

Tags: name语言title方向itemaretechprogrammer
3条回答

试试这个:

def main():
    duplicate = 0
    employees = [
        {'name': 'John', 'empID': '102', 'dpt': 'tech', 'title': 'programmer', 'salary': '75'},
        {'name': 'Jane', 'empID': '202', 'dpt': 'tech', 'title': 'programmer', 'salary': '80'},
        {'name': 'Joe', 'empID': '303', 'dpt': 'accounting', 'title': 'accountant', 'salary': '85'}
    ]
    tech_dep = 0
    accounting_dep = 0
    for item in employees:
        if item['dpt'] == 'tech':
            tech_dep += 1
        elif item['dpt'] == 'accounting':
            accounting_dep += 1

    print('Number of Employees from tech dep are : ', tech_dep)
    print('Number of Employees from accounting dep are : ', accounting_dep)


main()

它会给你这样的输出:

^{pr2}$

注意:

这是对您问题的简单回答,因为正如您所说,您是python的新手,所以我想给您一个简单的答案!另外请注意,您在问题中创建字典的方式是错误的,您可以创建字典字典或字典列表。而且,@Austin刚才给你的答案也很简单,它显示了counter的用法。在

希望这对你有帮助!:)

使用^{}

from collections import Counter

employees = [{'name': 'John', 'empID': '102', 'dpt': 'tech', 'title': 'programmer', 'salary': '75'},
             {'name': 'Jane', 'empID': '202', 'dpt': 'tech', 'title': 'programmer', 'salary': '80'},
             {'name': 'Joe', 'empID': '303', 'dpt': 'accounting', 'title': 'accountant', 'salary': '85'}]

dpts = [x['dpt'] for x in employees]
print(Counter(dpts))

# Counter({'tech': 2, 'accounting': 1})

如果您不想导入Counter,请使用字典跟踪每个部门的员工人数:

employee_list = [{
    'name': 'John',
    'empID': '102',
    'dpt': 'tech',
    'title': 'programmer',
    'salary': '75'
}, {
    'name': 'Jane',
    'empID': '202',
    'dpt': 'tech',
    'title': 'programmer',
    'salary': '80'
}, {
    'name': 'Joe',
    'empID': '303',
    'dpt': 'accounting',
    'title': 'accountant',
    'salary': '85'
}]

department_to_count = dict()
for employee in employee_list:
    department = employee["dpt"]

    if department not in department_to_count:
        department_to_count[department] = 0

    department_to_count[department] += 1

for department, employee_count in department_to_count.items():
    print("Department {} has {} employees".format(department,
                                                  employee_count))

相关问题 更多 >