vishu rathore
vishu rathore

Reputation: 1079

How to check if all values of a dictionary are 0

I want to check if all the values, i.e values corresponding to all keys in a dictionary are 0. Is there any way to do it without loops? If so how?

Upvotes: 92

Views: 111042

Answers (4)

Fanchi
Fanchi

Reputation: 787

You can use the [any()]1 method, basically it checks for boolean parameters, but 0 will act as False in this case, and any other number as True.

PY3:

dict1 = {"a": 0, "b": 1}
dict2 = {"a": 0, "b": 0}

print(not any(dict1.values()))
print(not any(dict2.values()))
enter code here

Try this code PY2:

dict1 = {"a": 0, "b": 1}
dict2 = {"a": 0, "b": 0}

print not any(dict1.itervalues())
print not any(dict2.itervalues())

Output:

False
True

Edit 2: one sidenote/caution, calling any() with an empty list of elements will return False.

Edit 3: Thanks for comments, updated the code to reflect python 3 changes to dictionary iteration and print function.

1: https://docs.python.org/2/library/functions.html#any

Upvotes: 15

timgeb
timgeb

Reputation: 78700

With all:

>>> d = {1:0, 2:0, 3:1}
>>> all(x==0 for x in d.values())
False
>>> d[3] = 0
>>> all(x==0 for x in d.values())
True

No matter whether you use any or all, the evaluation will be lazy. all returns False on the first falsy value it encounters. any returns True on the first truthy value it encounters.

Thus, not any(d.values()) will give you the same result for the example dictionary I provided. It is a little shorter than the all version with the generator comprehension. Personally, I still like the all variant better because it expresses what you want without the reader having to do the logical negation in his head.

There's one more problem with using any here, though:

>>> d = {1:[], 2:{}, 3:''}
>>> not any(d.values())
True

The dictionary does not contain the value 0, but not any(d.values()) will return True because all values are falsy, i.e. bool(value) returns False for an empty list, dictionary or string.

In summary: readability counts, be explicit, use the all solution.

Upvotes: 10

Shawn
Shawn

Reputation: 1943

use all():

all(value == 0 for value in your_dict.values())

all returns True if all elements of the given iterable are true.

Upvotes: 187

the_unknown_spirit
the_unknown_spirit

Reputation: 2586

You may also do it the other way using any :

>>> any(x != 0 for x in somedict.values())

If it returns True , then all the keys are not 0 , else all keys are 0

Upvotes: 4

Related Questions