'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!
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |