I am not sure how to write a logic in the most pythonic way.
I have 2 data types:
d: Dict[str, Any] = {} l: List[str]: []
Now I want to write a condition where I check if at least one of the strings is in either the dictionary(as a key) or in list. I am not sure how to do that in the most pythonic way.
I could obviously write:
if 'str_1' in d.keys() or 'str_2' id d.keys():
return True
elif 'str_1' in l or 'str_2' id l:
return True
I am struggling to come up with a way to write this elegantly in a Pythonic way, preferably to have it in one line.
CodePudding user response:
Perhaps something like this:
any(item in coll_ for coll_ in (l, d) for item in (‘str_1’,’str_2’))
CodePudding user response:
use a ternary expression like this:
l=["a","c"]
d={'b':'yes'}
key = 'b'
result = True if key in d or key in l else False
Clarification
The above is the equivalent of:
result = key in d or key in l
In a ternary expression you are not forced to return boolean.