首页 > 解决方案 > 如何在python中为字典使用计数器

问题描述

我正在尝试计算员工头衔

我已经尝试了很多,但我认为我没有正确地将它们应用到场景中。

employees = [
    {
        "email": "jonathan2532.calderon@gmail.com",
        "employee_id": 101,
        "firstname": "Jonathan",
        "lastname": "Calderon",
        "title": "Mr",
        "work_phone": "(02) 3691 5845"
    }]





EDIT:

from collections import Counter

class Employee:
    def __init__(self, title,):
        self.title = title

title_count = Counter()

for employee in [Employee("title") for data in employees]:
    title_count[employee.title,] += 1

print(title_count)

Counter({('title',): 4})

我似乎无法获得那里的具体名称。

标签: pythonpython-3.x

解决方案


这里有几件事,欢迎堆栈溢出。请阅读如何提出一个好问题。接下来,python 试图帮助你解决它给你的错误。

尝试将错误的一部分复制并粘贴到谷歌中。然后,访问有关您尝试使用的数据类型的文档。我认为你的问题已经过编辑,但是是的——它仍然会有所帮助。

最后,我们需要看一个最小的、完整的、可验证的例子。所以,代码,我们需要看看你试图用什么样的代码来解决你的问题。

考虑数据的结构会有所帮助:

from collections import Counter

class Employee:
    def __init__(self, title, employee_id):
        # all other fields omitted
        self.title = title
        self.employee_id = employee_id

这是您的问题的一些最小数据(可以说您可以使用更少的数据)。

employees = [
    {
        "title": "Mr",
        "employee_id": 1
    },
    {
        "title": "Mr",
        "employee_id": 2
    },
    {
        "title": "Mrs",
        "employee_id": 3
    },
    {
        "title": "Ms",
        "employee_id": 4
    }
]

定义其他必要的数据结构。

title_count = Counter()

# Just to demo results.
for employee in [Employee(**data) for data in employees]:
    print(f"title: {employee.title} id: {employee.employee_id}")

我会把**data符号留给谷歌。但是现在你有一些结构良好的数据,并且可以相应地处理它。

# Now we have some Employee objects with named fields that are
# easier to work with.
for employee in [Employee(**data) for data in employees]:
    title_count[employee.title] += 1

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

推荐阅读