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

时间:2019-03-29 13:38:10

标签: python dictionary

我已经尝试了一段时间,而不是最擅长编程的人。这是我到目前为止所拥有的。

字典的键应为 列出并列出具有该特定职务的员工人数。

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}

3 个答案:

答案 0 :(得分:1)

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的值,如果None不存在,则返回title

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以使用计数器进行此操作

from collection import Counter
titles = [e['title'] for e in employees]
counts = Counter(titles)
# Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1})