Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Searching multiple values in list and performing multiple operations

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.

like image 325
express_v2 Avatar asked Dec 24 '22 05:12

express_v2


1 Answers

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
like image 146
Andrej Kesely Avatar answered Dec 25 '22 18:12

Andrej Kesely