Home > Software engineering >  how to access an element in a nested dictionary?
how to access an element in a nested dictionary?

Time:04-28

how can I access cost in

coffee={"cappuccino":{"ingredients":{"water":250,"milk":100},"cost":45}}

CodePudding user response:

cappuccino_cost = coffee["cappuccino"]["cost"]

CodePudding user response:

Think about it backwards. If you already had cappuccino

cappuccino = {"ingredients":{"water":250,"milk":100},"cost":45}}

then how you would retrieve "cost"? You might already know that you can do it like this

cappuccino["cost"]

Now think about how you can get cappuccino from coffee.

coffee = {"cappuccino": {"ingredients": ... }}

Its the same idea as before

cappuccino = coffee["cappuccino"]

You can write it all out in separate lines if its clearer to you. Given that you have

coffee={"cappuccino":{"ingredients":{"water":250,"milk":100},"cost":45}}

You can write

cappuccino = coffee["cappuccino"]
cost = cappuccino["cost"]

Or you can be more concise and do it in one line. Take the last line, cost = cappuccino["cost"] and replace cappuccino with coffee["cappuccino"].

cost = coffee["cappuccino"]["cost"]
  • Related