如何在字典中计算相同的值? [英] How to count the same values in a dict?

查看:92
本文介绍了如何在字典中计算相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的dict:

I have a dict that looks like this:

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

我想做的是,对相同的值进行计数,以使我知道yes发生了3次,no发生了2次,maybe发生了1次.

What i want to do is, counting the same values so that i know that yes occurred 3 times, no occurred 2 times and maybe occurred 1 time.

我现在要做的是:

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

它工作正常,但是肯定有更好的方法来做到这一点.什么是更Python化的方式来做到这一点?

It works fine but there is for sure a better way to do this. What would be a more pythonic way to do this?

推荐答案

您可以将诸如dict.values之类的可迭代内容提供给collections.Counter:

You can feed an iterable such as dict.values to 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})

这篇关于如何在字典中计算相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆