I have a python dictionary object that contains a boolean for every key, e.g.:
d =开发者_StackOverflow社区 {'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())
sum(d.values())
a.values().count(True)
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.
The Answer is you have to convert the dict_values into list and use count()
d = {'client1': True, 'client2': False}
list(d.values()).count(True)
Ans will be: 1
精彩评论