Number of occurrences of the number of elements in the dictionary

Asked 5 months ago, Updated 5 months ago, 6 views

I'd like to count the number of dictionary elements in python and output them as a list.
What kind of code should I write?(I'm sorry, but I wrote the following coat.)

for vin max (partition.values()):
    l=list(p.values()) .count(v)

The data in p looks like the following.For example, I would like to know how many of them correspond to "0".

{'Anko':0, 'Chocolate':0, 'Candy':0, 'Cookie':0, 'Sashimi':2, 'Flour':1, 'Tempura':1, 'Chikuwa':2, 'Marshmallow':0, 'Meat and potatoes':2,


2022-09-30 14:21

1 Answers

To be honest, "count the number of values equal to zero":

 sum ([1 for vin p.values() if v==0])

You can also write as a generator or use True to be treated as 1:

sum(v==0 for vin p.values())

collections.Counter is useful if you want to count multiple values:

 from collections import Counter

cp = Counter(p.values())

Note: count the number of occurrences of a certificate value in a dictionary in python? -- English Stack Overflow

2022-09-30 14:21

If you have any answers or tips

© 2023 OneMinuteCode. All rights reserved.