Reputation: 131
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.
Upvotes: 4
Views: 6221
Reputation: 9977
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 @staticmethod
s 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.
Upvotes: 1
Reputation: 444
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
Upvotes: 1
Reputation: 1439
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
Upvotes: 2
Reputation: 6748
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)]
Upvotes: 0
Reputation: 2729
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
Upvotes: 0
Reputation: 195438
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
Upvotes: 6