How to check if all values of a dictionary are 0

Question:

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?

Asked By: vishu rathore

||

Answers:

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.

Try this code PY2:

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

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

PY3:

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

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

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

Answered By: Fanchi

use all():

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

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

Answered By: Shawn

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.

Answered By: timgeb

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

Answered By: the_unknown_spirit
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.