astrofrog
astrofrog

Reputation: 34091

Counting booleans in 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?

Upvotes: 13

Views: 10982

Answers (5)

Dileep Hs
Dileep Hs

Reputation: 1

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

Upvotes: 0

Martin DeMello
Martin DeMello

Reputation: 12336

a.values().count(True)

Upvotes: 3

Alex Martelli
Alex Martelli

Reputation: 881575

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.

Upvotes: 1

SilentGhost
SilentGhost

Reputation: 319561

sum(d.values())

Upvotes: 4

Ants Aasma
Ants Aasma

Reputation: 54882

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

Upvotes: 28

Related Questions