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?
Method #2 : Using set() + values() + len() This is yet another way in which this task can be performed. In this, we extract all the values using values() and set() is used to remove duplicates. If length of the extracted set is 1, then all the values are assumed to be similar.
# Checking if a dictionary is empty by using the any() function empty_dict = {} if any(empty_dict): print('This dictionary is not empty! ') else: print('This dictionary is empty! ') # Returns: This dictionary is empty!
Check if a value exists in a dictionary: in operator, values() To check if a value exists in a dictionary, i.e., if a dictionary has/contains a value, use the in operator and the values() method. Use not in to check if a value does not exist in a dictionary.
use all()
:
all(value == 0 for value in your_dict.values())
all
returns True
if all elements of the given iterable are true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With