简体   繁体   中英

python get number of occurences of given pattern in a dict

I have a dictionary as following:

adict = {'instr1' : "yes", 'instr2' : "yes", 'instr3' : "yes", 'instr4' : "no"}

Is there an easy method to get the number of "yes" in the dictionary?

You can use collections.Counter :

>>> adict = {'instr1' : "yes", 'instr2' : "yes", 'instr3' : "yes", 'instr4' : "no"}
>>> import collections
>>> collections.Counter(adict.values())
Counter({'yes': 3, 'no': 1})

You can use sum and a generator expression:

>>> sum(1 for x in adict.itervalues() if x == 'yes')
3

As True == 1 , so this is also valid:

sum( x == 'yes' for x in adict.itervalues())

Another option is list.count , this is going to be fast compared to sum() , but creates a list of all values in the memory:

>>> adict.values().count('yes')
3

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