Take, for instance this dictionary of minerals, and foods that contain those minerals as mineral:food key:value pairs (D)-
D = {'copper': {'Tomatoes', 'Onions', 'Eggplant', 'Grapes', 'Bell Peppers'}, 'manganese': {'Tomatoes', 'Onions', 'Eggplant', 'Grapes', 'Garlic', 'Celery', 'Bell Peppers'}, 'magnesium': {'Onions'}, 'phosphorus': {'Onions'}, 'potassium': {'Celery', 'Tomatoes', 'Grapes'}, 'sodium': {'Celery', 'Butter'}, 'salt': {'Celery', 'Butter'}}
I'm trying to write a function (I'm assuming now a regular expression), that takes a string of 3 minerals, and returns a set of the foods that contain those minerals.
For instance, for the input: 'copper & manganese & phosphorus'
I would need the output to be: {Onions}
Because onions are the only food that contain all 3 minerals. (Using AND (not OR) logic).
So I need to check the dictionary only for keys that contain all 3 values.
Right now I was able to come up with the following, which does what I want, only using "OR" logic. As in, it returns all of the keys that contain any of those values.
D = {'copper': {'Tomatoes', 'Onions', 'Bell Peppers', 'Eggplant', 'Grapes'}, 'manganese': {'Tomatoes', 'Onions', 'Bell Peppers', 'Celery', 'Eggplant', 'Garlic', 'Grapes'}, 'magnesium': {'Onions'}, 'phosphorus': {'Onions'}, 'potassium': {'Tomatoes', 'Celery', 'Grapes'}, 'sodium': {'Butter', 'Celery'}, 'salt': {'Butter', 'Celery'}}
mList = ['copper', 'magnesium', 'manganese', 'phosphorus', 'potassium', 'salt', 'sodium']
x = []
y = [D[k] for k in mList if k in D]
for s in y:
for r in s:
if r not in x:
x.append(r)
x = sorted(x)
sx = set(x)
return(sx)
Returns:
{'Tomatoes', 'Onions', 'Bell Peppers', 'Celery', 'Eggplant', 'Garlic', 'Grapes'}