views:

89

answers:

4

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?

+12  A: 

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())
Ants Aasma
+1 for explanation.
Aaron Digulla
+2  A: 
sum(d.values())
SilentGhost
Simple and general, one only has to know that booleans are also integers in Python, and specifically 0 and 1 (not surprisingly).
kaizer.se
that's what docs are for: http://docs.python.org/library/stdtypes.html#boolean-values
SilentGhost
+1  A: 

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.

Alex Martelli
+1  A: 
a.values().count(True)
Martin DeMello
clear, but not as clear as using `sum()` IMO. Will stop working when Python 3's `dict.values` returns an interable view, not a list.
kaizer.se
how is it not as clear as using "sum"? it reads "count the number of elements in values() whose value is True"; it is a direct translation of the problem whereas sum() introduces one level of conceptual indirection.
Martin DeMello