Check if statement true for all list items [duplicate] - python

This question already has answers here:
Check if any value of a dictionary matches a condition [duplicate]
(2 answers)
Closed 3 years ago.
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?

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

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

Related

Find most elegant way to return key if condition is set to true

I have a python dictionary
slot_a = 'a'
slot_b = 'b'
# dict which lists all possible conditions
con_dict = {"branch_1": slot_a == 'a' and slot_b == 'b',
"branch_2": slot_a == 'a' and slot_b == 'c'}
Now I want to return the key for the first true condition. In this case it's branch_1.
My solution is:
# Pick only the condition which is set to True
true_branch = [k for k, v in con_dict.items() if v == True]
true_branch
>>> branch_1
Since the number of branches can be very long, I was wondering, if there might be a more elegant way to get the same result?! Maybe if / elif / else and then return key? Or even something completely different? All I need at the end is the name of the true condition. Therefore working with a dict may not even be necessary.
Just asking for inspiration!
You could try to use an iterator. It will stop as soon it gets the first match without going through the whole "object".
ks, vs = zip(*con_dict.items()) # decoupling the list of pairs
i = 0
vs = iter(vs) # terms are all booleans
while not next(vs):
i += 1
del vs # "free" the iterator
print(ks[i])
or
true_branch = next((k for k, condition in con_dict.items() if condition), None)
print(true_branch)

How to skip a line of code based on certain condition? python dictionary min [duplicate]

This question already has answers here:
How to check if a dictionary is empty?
(9 answers)
Closed 1 year ago.
in python:
dic = {} #start with an empty list
After this line, I did a series of command to add things to the dic. But there is also a situation where nothing is added. Then, I need to use the value in the dic.
a = min(dic, key=dic.get)
if there is nothing in the dic, it will give me an error:
ValueError: min() arg is an empty sequence I don't need an output for a if dic is empty, so I then attempted to use the if statement to get away:
if dic == None:
pass
else:
a = min(dic, key=dic.get)
but this will still give me the same error. Is there a way to skip this line of codea = min(dic, key=dic.get)when dic = {}?
The dic is of the <class dict> whereas the None object is of the <class 'Nonetype'>.
So the given expression dic == Nonewill always return False.
Instead change it to dic == {} or len(dic) == 0 or simply dic.
An empty dictionary will usually evaluate to False.
if dic:
pass
else:
a = min(dic, key=dic.get)
Try changing the logic to:
if len(dic) == 0:
pass
else:
a = min(dic, key=dic.get)
You current code skips over the pass block because even if the dict dic is empty, it is not None, there's a bunch of ways to check emptiness of a dict, personally, I'm a fan of checking the len as above but there are other way such as on this page.

Set A is empty but the code "elif A=={}:" doesn't work [duplicate]

This question already has answers here:
Creating an empty set
(4 answers)
Closed 2 years ago.
I'm writing code which checks whether the sum of subset could be S or not
Set={1,3,7}
sum=10
def subset_sum(A,S):
if S==0: return True
else if S<0: return False
else if A=={}: return False
else:
z=A.pop()
C=subset_sum(A-{z},S-z)
D=subset_sum(A-{z},S)
return C or D
print(subset_sum(Set,sum))
when I debug it, A is empty before this code else if A=={}: return False but this code goes to else: z=A.pop()
and makes error
Can't understand the reason
Can you elaborate it?
{} is an empty dictionary, not a set, instead check for empty set using len():
Set={1,3,7}
sum=10
def subset_sum(A,S):
if S==0:
return True
elif S<0:
return False
elif len(A)==0:
return False
else:
z=A.pop()
C=subset_sum(A-{z},S-z)
D=subset_sum(A-{z},S)
return C or D

Return true if list is not empty [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 2 years ago.
What is the most pythonic way to return true if a list is not empty?
def fun(x):
return x != []
Given some function called fun where we pass in a list x. List could look like [] or [1,3,4].
I want to return True if the list is not empty. Am I doing that in the most pythonic way?
The reason I ask is because when I do return x is not None instead of return x != [] I get a different answer. I guess this is because empty list is not considered null?
You can check the length of the list to see how many items are inside:
def fun(x):
return len(x) > 0
Or you can cast bool to be more pythonic:
def fun(x):
return bool(x)

My code is checking only 1 if condition in a function [duplicate]

This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed 3 years ago.
def check(str):
if(str.isalnum())==True:
return True
if(str.isalpha())==True:
return True
if(str.isdigit())==True:
return True
if(str.islower())==True:
return True
if(str.isupper())==True:
return True
if __name__ == '__main__':
s = input()
if(check(s)):
print('True')
else:
print('False')
It is showing only one condition's result. For example, if I type qA2 it is showing one True instead of
True
True
True
True
True
This is because you are "returning" from the function if one of the if conditions evaluates to true.
You can read more about the keyword return here.
The gist is, as the word says, it "returns" from the function with specified value(s).
If you want the other if conditions to get evaluated too, you will need to maintain a small data structure of all successful if conditions, eg:
def check(str):
# let's initialise a dictionary with all False values.
# If any if condition turns True, then we will set
# that value to True in the dictionary.
res = {
"isalnum":False,
"isalpha":False,
"isdigit":False,
"islower":False,
"isupper":False,
}
if(str.isalnum())==True:
res["isalnum"] = True
if(str.isalpha())==True:
res["isalpha"] = True
if(str.isdigit())==True:
res["isdigit"] = True
if(str.islower())==True:
res["islower"] = True
if(str.isupper())==True:
res["isupper"] = True
return res # This returns a dictionary with all values
if __name__ == '__main__':
s = input()
if(check(s)):
print('True')
else:
print('False')
return leaves the function immediately. The first condition which succeeds will cause the rest to be skipped, the way you defined your function.
If you want to check all the conditions every time, try something like
def check(str):
whether = True
if not str.isalnum():
whether = False
if not str.isalpha():
whether = False
if not str.isdigit():
whether = False
if not str.islower():
whether = False
if not str.isupper():
whether = False
return whether
Printing something in each branch seems excessive, but could certainly be added.
return stops the function's execution. Nothing after a return statement will be run, and a function can only have a single return value. If you want to see the result for all conditions, store them in a List or a Dict and return that instead, for example:
def check(str):
results = {}
results['isalnum'] = str.isalnum()
results['isalpha'] = str.isalpha()
results['isdigit'] = str.isdigit()
results['islower'] = str.islower()
results['isupper'] = str.isupper()
return results

Categories