Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting booleans in dictionary

I have a python dictionary object that contains a boolean for every key, e.g.:

d = {'client1': True, 'client2': False}

What is the easiest and most concise way to count the number of True values in the dictionary?

like image 720
astrofrog Avatar asked Oct 22 '09 15:10

astrofrog


People also ask

How do you count Booleans in Python?

Use count_nonzero() to count True elements in NumPy array In Python, False is equivalent to 0 , whereas True is equivalent to 1 i.e. a non-zero value.

How do you count values in a dictionary?

Use len() to count dictionary items The len() method returns the total length of a dictionary, or more precisely, the total number of items in the dictionary.

Can you use count on a dictionary in Python?

Python dictionary count keys By using the len() function we can easily count the number of key-value pairs in the dictionary.


1 Answers

For clarity:

num_true = sum(1 for condition in d.values() if condition)

For conciseness (this works because True is a subclass of int with a value 1):

num_true = sum(d.values())
like image 83
Ants Aasma Avatar answered Sep 22 '22 17:09

Ants Aasma