Dav*_*yer 4 python counter dictionary
我有一个dict看起来像这样:
"votes": {
"user1": "yes",
"user2": "no",
"user3": "yes",
"user4": "no",
"user5": "maybe",
"user6": "yes"
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是,计算相同的值,以便我知道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
Run Code Online (Sandbox Code Playgroud)
它工作正常,但肯定有更好的方法来做到这一点.什么是更pythonic方式来做到这一点?
您可以养活一个可迭代如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})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
926 次 |
| 最近记录: |