accessing a nested dictionary in python

Question:

I have this nested dictionary that I want to access:

menu = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

I want to access the first "cost" (espresso) in this nested dictionary, I tried doing menu["cost"], but it won’t work, can anyone help?

Asked By: Helal_Python

||

Answers:

To get the cost of a specific item,

cost = menu["espresso"]["cost"]
# 1.5

For future reference,

If you wanted a list of all the prices,

costs = [item["cost"] for item in menu.values()]
# [1.5, 2.5, 3.0]

If you wanted a list of tuples of item_name, cost,

costs = [(key, value["cost"]) for key, value in menu.items()]
# [('espresso', 1.5), ('latte', 2.5), ('cappuccino', 3.0)]

If you wanted a dictionary of item_name: cost,

costs = {key : value["cost"] for key, value in menu.items()}
# {'espresso': 1.5, 'latte': 2.5, 'cappuccino': 3.0}
Answered By: Samathingamajig
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.