如何统计字典中相同值的数量?

5

我有一个类似这样的dict

"votes": {
    "user1": "yes",
    "user2": "no",
    "user3": "yes",
    "user4": "no",
    "user5": "maybe",
    "user6": "yes"
}

我想做的是,统计相同的值,以便我知道yes出现了3次,no出现了2次,maybe出现了1次。

目前我的做法是这样的:

votes = OrderedDict()
for key, value in vote_dict["votes"].items():
    if value in votes:
        votes[value] += 1
    else:
        votes[value] = 1

这样做是可行的,但肯定有更好的方法。有什么更符合Python风格的方法吗?

1个回答

19
你可以将可迭代对象(例如dict.values)传递给collections.Counter
from collections import Counter

votes = {"user1": "yes", "user2": "no", "user3": "yes",
         "user4": "no", "user5": "maybe", "user6": "yes"}

res = Counter(votes.values())

print(res)

Counter({'yes': 3, 'no': 2, 'maybe': 1})

1
实际上,由于我需要一个有序计数器,这也很有趣:https://dev59.com/uVsW5IYBdhLWcg3wDzrs - Endogen
1
请注意,在Python 3.6(作为实现细节)和3.7+(官方版本)中,字典是按插入顺序排序的。由于这也适用于dict的子类,因此collections.Counter也是按插入顺序排序的。 - jpp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接