1

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

3
  • for key,value in MENU["product_2"]["ingredients"].items(): print(value) Commented Jun 14 at 20:11
  • Or print(MENU["product_2"]["ingredients"].values()) Commented Jun 14 at 20:12
  • 1
    Do you see that the loop variable ingredient is not actually used in the loop? That's usually a sign that you've made some mistake. Commented Jun 14 at 20:14

3 Answers 3

1

If you want all values, iterate over them as a hierarchy.

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

Check out this explanation about dictionaries in python with examples

1

You need to get the value from the iterated dictionary keys:

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

Or if you just want from product_2:

print(MENU["product_2"]["ingredients"].values())

If you want the keys:

print(list(MENU["product_2"]["ingredients"]))

Or:

print(MENU["product_2"]["ingredients"].keys())
0
0

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]
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.