python 打印dic>dic值[重复]

nwsw7zdq  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(118)
    • 此问题在此处已有答案**:

Iterate the keys and values from the dictionary(3个答案)
10小时前关闭。

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,
    }
}

我只能打印第一个dic(咖啡名称)键,但由于某种原因,我无法达到的成本...

for item in MENU:
    for item2,cost in item:
        print(f" {item} {cost} ")
t98cgbkg

t98cgbkg1#

如果不传递键名(在本例中为'cost'),就无法神奇地获取字典值。

for item, data in MENU.items():
    print(f"Item {item}, cost: {data['cost']}")

这应该打印

Item espresso, cost: 1.5
Item latte, cost: 2.5
Item cappuccino, cost: 3.0

相关问题