Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Python, how to code for searching food names by their ingredients?

The below lists food names and ingredients.

Pasta: tomato, onion, parsley, wine, flour.
Lasagna: tomato, beef, cheese, flour, 
Ramen: beef, onion, flour. 

I like to find food names by ingredients.

For example, if I like to find food names which has ‘flour’ and ‘onion’, the answer should be ‘Pasta’ and ‘Ramen’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I like to find food names which has ‘beef’ and ‘flour’, the answer should be ‘Lasagna’ and ‘Ramen’.

The number of ingredients for searching can be more than two or just one.

Firstly, I tried it with dict, but it did not help. Next, I tried with table, but it was hard because each food has different number of ingredients.

Please help me with this.

EDIT: I am sorry for not including my try. I usually do, but for this question, I have no idea how to use dict. Also I am not even able to generate a table because the number of ingredients are different. The below is my failed attempt.

x = {'Pasta':['tomato', 'onion', 'parsley', 'wine', 'flour'],
     'Lasagna':['tomato', 'beef', 'cheese', 'flour'],
     'Ramen':['beef', 'onion', 'flour']}

test = ['tomato', 'flour']

[k for k in enumerate(x.values()) if test in k]

>Solution :

This works; use a dictionary to keep your ingredients, and then search through values of the dictionary:

db = {"Pasta": ["tomato", "onion", "parsley", "wine", "flour"],
      "Lasagna": ["tomato", "beef", "cheese", "flour"], 
      "Ramen": ["beef", "onion", "flour"] }


test = {"onion","flour"}

for k, v in db.items():
    if test.issubset(set(v)) :
        print(k)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading