Search code examples
pythondictionaryfor-loopnestediteration

How to iterate through a dictionary to get values on the lowest level?


Please help me understand how to extract the value of each ingredient for each product and do something with it. But for starters I just want to print them all one by one.

MENU = {
    "product_1": {
        "ingredients": {
            "ingredient_1": 50,
            "ingredient_2": 18
        },
        "cost": 1.5
    },
    "product_2": {
        "ingredients": {
            "ingredient_1": 200,
            "ingredient_2": 150,
            "ingredient_3": 24
        },
        "cost": 2.5
    }
}

I started with this code:

for ingredient in MENU:
   print(MENU["product_2"]["ingredients"])

but this prints out all 3 ingredients with their values for product_2 3 times. I need it to print out 200, 150, 24


Solution

  • As @John commented:

    You need to get familiarized yourself with dictionary:

    for key,value in MENU["product_2"]["ingredients"].items():
      print(value)
    

    or

    for x in MENU["product_2"]["ingredients"].values():
      print(x)
    

    Output

    200
    150
    24
    

    If you just need a list:

    list(MENU["product_2"]["ingredients"].values())
    #[200, 150, 24]