猿问

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

我一直试图弄清楚它有一段时间了,而不是最擅长编程。这是我到目前为止所拥有的。


字典的键应该是列表中员工的头衔,值是具有该特定头衔的员工数。


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 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}


噜噜哒
浏览 167回答 3
3回答

胡子哥哥

collections.Counterfrom collections import Countercounts = 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

呼啦一阵风

使用 collections.defaultdict前任:from collections import defaultdictresult = defaultdict(int)for i in employees:&nbsp; &nbsp; result[i["title"]] += 1print(result)输出:defaultdict(<type 'int'>, {'Mrs': 1, 'Ms': 1, 'Mr': 2})

米琪卡哇伊

你可以用一个计数器来做到这一点:from collection import Countertitles = [e['title'] for e in employees]counts = Counter(titles)# Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1})
随时随地看视频慕课网APP

相关分类

Python
我要回答