为了账号安全,请及时绑定邮箱和手机立即绑定

我如何计算字典中每个标题的数量

我如何计算字典中每个标题的数量

噜噜哒 2021-12-21 17:42:08
我一直试图弄清楚它有一段时间了,而不是最擅长编程。这是我到目前为止所拥有的。字典的键应该是列表中员工的头衔,值是具有该特定头衔的员工数。employees = [    {        "email": "jonathan2532.calderon@gmail.com",        "employee_id": 101,        "firstname": "Jonathan",        "lastname": "Calderon",        "title": "Mr",        "work_phone": "(02) 3691 5845"    },    {        "email": "christopher8710.hansen@gmail.com",        "employee_id": 102,        "firstname": "Christopher",        "lastname": "Hansen",        "title": "Mr",        "work_phone": "(02) 5807 8580"    },    {        "email": "isabella4643.dorsey@gmail.com",        "employee_id": 103,        "firstname": "Isabella",        "lastname": "Dorsey",        "title": "Mrs",        "work_phone": "(02) 6375 1060"    },    {        "email": "barbara1937.baker@gmail.com",        "employee_id": 104,        "firstname": "Barbara",        "lastname": "Baker",        "title": "Ms",        "work_phone": "(03) 5729 4873"    }]#my workfor i in employees:    print(i['title'])employees.count('title')print()#my output:MrMrMrsMs#expected output:{'Ms': 1, 'Mrs': 1, 'Mr': 2}
查看完整描述

3 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

collections.Counter


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或返回的值。Nonetitle


查看完整回答
反对 回复 2021-12-21
?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

使用 collections.defaultdict


前任:


from collections import defaultdict


result = defaultdict(int)

for i in employees:

    result[i["title"]] += 1

print(result)

输出:


defaultdict(<type 'int'>, {'Mrs': 1, 'Ms': 1, 'Mr': 2})


查看完整回答
反对 回复 2021-12-21
?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

你可以用一个计数器来做到这一点:


from collection import Counter

titles = [e['title'] for e in employees]

counts = Counter(titles)

# Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1})


查看完整回答
反对 回复 2021-12-21
  • 3 回答
  • 0 关注
  • 166 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号