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

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

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

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