5

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?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Endogen
  • 589
  • 2
  • 12
  • 24

1 Answers1

18

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})
jpp
  • 159,742
  • 34
  • 281
  • 339
  • 1
    And actually, since i need to have a ordered counter, this is also interesting: https://stackoverflow.com/questions/35446015/creating-an-ordered-counter – Endogen Aug 26 '18 at 19:53
  • 1
    Note in Python 3.6 (as an implementation detail) and 3.7+ (official), dictionaries are insertion ordered. Since this also applies to subclasses of `dict`, `collections.Counter` is also insertion ordered. – jpp Nov 11 '19 at 14:43