I'm trying to search a list I have for specific values and if any of those values exist in the list, I would like to perform a different operation.
Currently this is the list I am working with:
print(categories)
['Creams', 'Bath', 'Personal Care']
What I would like to do is search this categories list for some different values. To do this, I've converted categories
into a set and am individually searching for each of the values with an if statement.
For example:
c = set(categories)
if "Conditioners" in c:
print("1")
if "Bath" in c:
print("2")
if "Shaving Gels" in c:
print("3")
Which returns:
2
What I would ideally like to do is put my criteria into a list or some other relevant data structure and have it perform that particular operation if that value exists within categories
in an efficient manner.
You can store your functions in dictionary, where values are desired functions. That way, you have easy access to them by keys and you can traverse categories normally:
categories = ['Creams', 'Bath', 'Personal Care']
my_dict = {
'Conditioners': lambda: print(1),
'Bath': lambda: print(2),
'Shaving Gels': lambda: print(3)
}
for category in categories:
fn = my_dict.get(category, lambda: None)
fn()
Output:
2
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