我一直试图弄清楚一段时间,而不是最擅长编程的人。这是我到目前为止所拥有的。
词典的关键字应该是列表中员工的头衔,并且应该是具有该特定标题的员工数的值。
employees = [
{
"email": "[email protected]",
"employee_id": 101,
"firstname": "Jonathan",
"lastname": "Calderon",
"title": "Mr",
"work_phone": "(02) 3691 5845"
},
{
"email": "[email protected]",
"employee_id": 102,
"firstname": "Christopher",
"lastname": "Hansen",
"title": "Mr",
"work_phone": "(02) 5807 8580"
},
{
"email": "[email protected]",
"employee_id": 103,
"firstname": "Isabella",
"lastname": "Dorsey",
"title": "Mrs",
"work_phone": "(02) 6375 1060"
},
{
"email": "[email protected]",
"employee_id": 104,
"firstname": "Barbara",
"lastname": "Baker",
"title": "Ms",
"work_phone": "(03) 5729 4873"
}
]
#my work
for i in employees:
print(i['title'])
employees.count('title')
print()
#my output:
Mr
Mr
Mrs
Ms
#expected output:
{'Ms': 1, 'Mrs': 1, 'Mr': 2}
from collections import Counter
counts = Counter([x['title'] for x in employees])
print(counts)
# Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1})
如果有任何没有title
字段使用的记录:
counts = Counter([x.get("title", None) for x in employees])
# Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1, None: 1})
在这里,.get
将获取的值,如果不存在,则title
返回。None
title
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句