Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the same values in a dict? [duplicate]

I have a dict that looks like this:

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

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.

What i do right now is this:

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

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

like image 315
Endogen Avatar asked Dec 08 '22 14:12

Endogen


1 Answers

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})
like image 195
jpp Avatar answered Dec 24 '22 12:12

jpp