close

How to check if all values of a dictionary are 0

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to check if all values of a dictionary are 0 in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to check if all values of a dictionary are 0?

  1. How to check if all values of a dictionary are 0?

    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.

  2. check if all values of a dictionary are 0

    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.

Method 1

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.

Method 2

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.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read