Question

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?

Was it helpful?

Solution

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())

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top