简体   繁体   中英

How to count the number of times a value appears in a dictionary?

I've been tasked with creating a "pown-chess" game, and i'm trying to figure out how to code the win condition. Is there any way to have python count the number of times a given value appears in a dictionary?

You can make a list of the dict's values, and use its count method.

result = list(mydict.values()).count(value)

The simplest way for a beginner (like me) is to apply Counter from collections to the values of your dictionary:

from collections import Counter
d=dict([(2,1),(3,1),(4,2),(5,1),(6,3),(7,2),(8,3)])
# d:(key,val) --> dd:(val,freq_of_val_in_d) 
dd=Counter(d.values())
print(dd)

gives:

Counter({1: 3, 2: 2, 3: 2})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM