Python – Searching multiple values in list and performing multiple operations

  • A+
Category:Languages

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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: