0

I have the following dictionary:

    dictionary = {'A':0, 'B':0, 'C':0, 'D':0}

I would like to check if all the values stored by the dictionary keys are zero and then execute some code. What I had in mind is something like:

    if (dictionary[k] == 0 for all k in dictionary.keys()):
        # do something

What I am currently doing is:

  if (dictionary['A'] == 0 and dictionary['B'] == 0 and dictionary['C'] == 0 and dictionary['D'] == 0):
      # do something

This seems very inefficient if my dictionary grows larger. Is there any way I could check a condition for all keys and demand all of them to be simultaneously true?

ma7642
  • 139
  • 2
  • 12

2 Answers2

1

Something like this should work, not very short but nice and readable

def check(dictionary):
    for value in dictionary.values():
        if value != 0:
            return False
    return True
if check({'A':0, 'B':0, 'C':0, 'D':0}):
    #do something

1

Check this function that can make your code look clean and you can change params as you wish.

# function that return True if all your dictionary values are equal to 0 and false if any value has a different value

def check(dictionary, val): 
    for key in dictionary:
        if dictionary[key]!= val: 
            return False 
    return True

if check(dictionary,0):
 #do something
Ilyas Oirraq
  • 43
  • 1
  • 7