4

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.

1
  • 2
    why not have the keywords in a dictionary that maps to functions that execute on the categories? Commented Aug 2, 2018 at 14:12

6 Answers 6

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

This is what I was looking for. Thank you!
Would you happen to know how I could do a different function if in the categories list, two or more of the keys in my_dict values as opposed to each individual function?
@express_v2 That's a little bit more complicated and the answer is long for comments. Feel free to open new question.
2

IIUC, this is what you're looking for. dict comprehension with enumerate. This will also reduce the amount of manual labor required so long as your list is in the order you want.

d = {k:v for v,k in enumerate(categories,1)}
d
{'Creams': 1, 'Bath': 2, 'Personal Care': 3}

You can perform whatever operation you want on the dictionary.

c = ['Conditioners','Bath','Shaving Gels']
for i in c:
    print (d.get(i, None))
None
2
None

Comments

1

Probably a dictionary would be a suitable datatype. You could complete your task like such.

diction = {"Conditioners": 1, "Bath": 2} #add whatever else you want

for item in categories:
        try:
           print(diction[item])
        except:
            continue

Comments

1

I'd like to suggest another neat and maintainable alternative to dictionaries. You could also create a class with @staticmethod and use getattr to call methods like so,

categories = ['Creams', 'Bath', 'Personal Care']

class CategoriesWorker:
    @staticmethod
    def Creams():
        print(1)
    @staticmethod
    def Bath():
        print(2)
    @staticmethod
    def PersonalCare():
        print(3)

for category in categories:
    try:
        getattr(CategoriesWorker, category.replace(" ", ""))()
    except AttributeError:
        pass

>>>
1
2
3

Note here that naming of your @staticmethods is crucial. I basically use a the same value without spaces and then strip them of the actual value in the list to retrieve it in the class.


Basically, I suggested this in order to overcome the problem where using a dictionary in conjunction with lambdas could lead to unreadable code. Indeed, your specific example ask to simply print() values. But what if the logic of the methods was more complicated ? You'd be writing a unreadable dictionary fast enough.

Now, an alternative you be to wrap the logic in a method and use it in a dictionary.

categories = ['Creams', 'Bath', 'Personal Care','test']
def Creams():
  print(1)

def Bath():
  print(2)

def PersonalCare():
  print(3)

comparison_dict = {'Creams':Creams,'Bath':Bath,'Personal Care':PersonalCare}


for category in categories:
  comparison_dict.get(category, lambda: None)()

>>>>
1
2
2

That would be valid also. I just like the class definition better since it is clear what this class intends to do and I like to have related code at one compact emplacement.

Comments

0
categories = ['Creams', 'Bath', 'Personal Care']
criteria = {"Conditioners" : "1", "Bath" : "2", "Shaving Gels" : "3"}

# loop through all the categories
for i in set(categories):
    # if the category is in the criteria print the value
    if i in criteria.keys():
        print(criteria[i]) #print 2

Comments

0

Something like this (for the exact case you put above)

a=['Creams', 'Bath', 'Personal Care']
b=['Conditioners','Bath','Shaving Gels']
[print(c-1) for c,e in b if e in enumerate(a)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.