如何使用python计算员工词典数据库中的值?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (28)

我正在尝试阅读每个部门有多少人,例如:tech-2,accounting-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")
提问于
用户回答回答于

如果你不想导入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))
用户回答回答于

使用collections.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})

扫码关注云+社区

领取腾讯云代金券