【问题标题】:How to count the same values in a dict? [duplicate]如何计算字典中的相同值? [复制]
【发布时间】:2019-02-01 07:14:09
【问题描述】:

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

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

我想要做的是,计算相同的值,以便我知道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

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

【问题讨论】:

    标签: python dictionary counter


    【解决方案1】:

    您可以将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})
    

    【讨论】:

    • 实际上,因为我需要一个订购柜台,这也很有趣:stackoverflow.com/questions/35446015/…
    • 注意在 Python 3.6(作为实现细节)和 3.7+(官方)中,字典是按插入顺序排列的。因为这也适用于dict 的子类,所以collections.Counter 也是插入排序的。
    猜你喜欢
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    相关资源
    最近更新 更多