python是我的新语言,所以这个问题听起来很简单,但是如果有人可以指出正确的方向,我将不胜感激!我创建了一个字典叫雇员的字典,它对他们具有一些价值:
我正在尝试阅读每个部门有多少人,例如: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))