简体   繁体   中英

Python: Count Values in multi-value Dictionary

How can I count the number of a specific values in a multi-value dictionary?

For example, if I have the keys A and B with different sets of numbers as values, I want get the count of each number amongst all of the dictionary's keys.

I've tried this code, but I get 0 instead of 2.

dic = {'A':{0,1,2},'B':{1,2}}
print(sum(value == 1 for value in dic.values()))

Counter is a good option for this, especially if you want more than a single result:

from collections import Counter

from itertools import chain
from collections import Counter
count = Counter(chain(*(dic.values())))

In the REPL:

>>> count
Counter({1: 2, 2: 2, 0: 1})
>>> count.get(1)
2

Counter simply tallies each item in a list. By using chain we treat a list of lists as simply one large list, gluing everything together. Feeding this right to Counter does the work of counting how many of each item there is.

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