How to check if all values of a dictionary are 0
PythonDictionaryPython Problem Overview
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?
Python Solutions
Solution 1 - Python
use all()
:
all(value == 0 for value in your_dict.values())
all
returns True
if all elements of the given iterable are true.
Solution 2 - Python
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.
Solution 3 - Python
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.
Solution 4 - Python
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