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?
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?
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())
In Python 2.*
, sum(d.itervalues()) is slightly less concise than the sum(d.values())
many are proposing (4 more characters;-), but avoids needlessly materializing the list of values and so saves memory (and probably time) when you have a large dictionary to deal with.
As some have pointed out, this works fine, because bools are ints (a subclass, specifically):
>>> False==0
True
>>> False+True
1
therefore, no need for circumlocutory if
clauses.