如何在python中使用counter作为字典

时间:2019-04-02 00:08:34

标签: python python-3.x

我正在尝试计算员工头衔

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

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

我似乎找不到那里的具体名称。

2 个答案:

答案 0 :(得分:0)

这里有几件事,欢迎堆栈溢出。请阅读how to ask a good question。接下来,python试图帮助您解决它给您的错误。

尝试将部分错误复制并粘贴到Google。然后,访问您尝试使用的data type上的文档。我认为您的问题已经过编辑,但是,是的–仍然会有所帮助。

最后,我们需要看到一个minimal, complete, and verifiable example。因此,代码,我们需要查看您尝试使用哪种代码来解决您的问题。

这有助于考虑数据的结构:

from collections import Counter

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

这里有一些 minimum 数据可以解决您的问题(可以减少使用)。

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表示法留给Google使用。但是现在您有了一些结构良好的数据,可以对其进行相应的处理。

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

答案 1 :(得分:0)

在您的示例中,for title in employees实际上在每次迭代中都会生成一个dict对象,因为雇员是dict对象的列表。虽然Counter接受dict映射作为输入,但它并不是您想要的。 cnt['title']只需将每次迭代的计数增加1,即可有效地计算出雇员列表中的dict对象的数量。

要按标题计数,您必须先解压缩列表中的每个dict对象。

from collections import Counter

titles = [e['title'] for e in employees]
>>>Counter(titles)
Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1})