问题
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?
回答1:
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})
来源:https://stackoverflow.com/questions/52027616/how-to-count-the-same-values-in-a-dict