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?
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.
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.
Python dictionary count keys By using the len() function we can easily count the number of key-value pairs in the dictionary.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With