skip to Main Content

I am working on my first coding project (interactive cookbook) and I have met a road block, I am trying to print the name of the array (chocolate chip cookies) by entering the ingredients name (flour) in the terminal, I am using python to do this. here’s an example of my json file code:

{
    "Recipes": [
        
     "chocolate chip cookie",[
        {
            "ingredients": "flour"
        },
        {
             "instructions": "Step 1: Preheat Oven to 375"  
        },
        {
            "category": "Cookies"
        }
         ]
    ]
}

here’s an excerpt of my python code:

response = input("are you looking for recipes with ingredients on hand (if so please enter 'ingredients') or are you looking for something to cook/bake? (if so please enter 'Cook/Bake')n")
if response == "ingredients":
    print("please enter ingredients")
    ingredients = input("enter ingredients separated by commas: ")
    ingredients = ingredients.split(",")
    for x in ingredients:
     import json 
     #pulling ingredients from cookbook.json(?)
     with open('cookbook.json', 'r') as f:
        data = json.load(f)

3

Answers


  1. It would be better to structure your data like this

    {
        "Recipes": [
            {   "name": "chocolate chip cookie",  
                "ingredients": [
                     "flour"
                ],
                "instructions": "Step 1: Preheat Oven to 375",  
                "category": "Cookies"
            }
             
        ]
    }
    

    Best to move the things you only need to do once, to the top of the code

    This includes the import and the reading of the JSON.

    import json 
    with open('cookbook.json', 'r') as f:
        cookbook = json.load(f)
    
    response = input("are you looking for recipes with ingredients on hand (if so please enter 'ingredients') or are you looking for something to cook/bake? (if so please enter 'Cook/Bake')n") 
    if response == "ingredients":
    
        print("please enter ingredients")
        ingredients_comma_separated = input("enter ingredients separated by commas: ")
        ingredients = ingredients_comma_separated.split(",")
    
        print("Matches for ingredient list", ingredients,":")
        for recipe in cookbook["Recipes"]:
            if all([ingredient in recipe["ingredients"] for ingredient in ingredients]):
                print(recipe)
    

    While you are testing the program, the question-and-answer pattern will drive you mad

    You would be better off with this sort of layout while you are developing. Later you can uncomment the questions.

    import json 
    #pulling ingredients from cookbook.json(?)
    with open('cookbook.json', 'r') as f:
        cookbook = json.load(f)
    
    # response = input("are you looking for recipes with ingredients on hand (if so please enter 'ingredients') or are you looking for something to cook/bake? (if so please enter 'Cook/Bake')n") 
    # if response == "ingredients":
    if True:
    
        # print("please enter ingredients")
        # ingredients_comma_separated = input("enter ingredients separated by commas: ")
        # ingredients = ingredients_comma_separated.split(",")
    
        available_ingredients = ["flour"]
        print("Matches for ingredient list", available_ingredients,":")
        for recipe in cookbook["Recipes"]:
            if all([ingredient in available_ingredients for ingredient in recipe["ingredients"]]):
                print(recipe)
    
    
        available_ingredients = ["flour","eggs"]
        print("Matches for ingredient list", available_ingredients,":")
        for recipe in cookbook["Recipes"]:
            if all([ingredient in available_ingredients for ingredient in recipe["ingredients"]]):
                print(recipe)
    
        available_ingredients = []
        print("Matches for ingredient list", available_ingredients,":")
        for recipe in cookbook["Recipes"]:
            if all([ingredient in available_ingredients for ingredient in recipe["ingredients"]]):
                print(recipe)
    
    Login or Signup to reply.
  2. Your data structure is quite unwieldy for the purpose at hand.

    • "Recipies" shoulf be a list of dictionaries (objects) rather than a list of alternating strings and lists
    • The attributes of a recipe should be held in a single dictionary rather than a list of one-key dictionaries
    • "ingredients" should be a list (otherwise it’s not much of a recipe if you don’t combine ingredients)

    Based on the data you do have, the process of finding a recipe name (overly complex as it may) could go as follows:

    data  = {
        "Recipes": [
            
         "chocolate chip cookie",[
            {
                "ingredients": "flour"
            },
            {
                 "instructions": "Step 1: Preheat Oven to 375"  
            },
            {
                "category": "Cookies"
            }
             ]
        ]
    }
    
    
    onHand = {"flour","chodolate"}
    
    recipe = [ name for name,recipe in zip(*[iter(data["Recipes"])]*2)
                    for fields in recipe for field,value in fields.items()
                    if field=="ingredients" and value in onHand ]
    
    ['chocolate chip cookie']
    
    Login or Signup to reply.
  3. First I would recomand chanign the structure of the json file to, for example:

    {"Recipes": [{
    "name":"chocolate chip cookie", 
    "ingredients": ["flour", "chocolate"], 
    "instructions": ["Preheat Oven to 375", "Preheat Oven to 375 again??"], "category": "Cookies"
    }]}
    

    Now you have a list called Recipes each item in this list will be a single recipe.

    Each recipe has 4 varialbes: name, ingredients, instructions, category.

    This way you can loop over every ingredient in every recipe to see if they match.

    If you only want to see the first result put a break in the is statement.

    for x in ingredients:
       for recipe in data['Recipes']:
          if x in recipe['ingredients']:
             print(recipe)
             break
    

    I also noticed that you put the import inside of the for loop, please don’t do this and put it at the top of the file to ensure that it only gets imported once.

    Also don’t put the with open() statments in the for loop. It’s best to use it once to read the data and save that data in a variable:

    import json 
    
    data = None
    
    with open('cookbook.json', 'r') as f:
        data = json.load(f)
    
    for x in ingredients:
        for recipe in data['Recipes']:
            if x in recipe['ingredients']:
                print(recipe['name])
                break
    

    To answer your initial question:

    • following the way I showed above , print(recipe[‘name]) will print the name.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search