-4
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 can only print the first dic (coffee names) keys, but for some reason I cannot reach the costs...

for item in MENU:
    for item2,cost in item:
        print(f" {item} {cost} ")
wjandrea
  • 28,235
  • 9
  • 60
  • 81
TPAL
  • 3
  • 3

1 Answers1

0

You can't magically fetch a dictionary value without passing the key name ('cost' in your case). Try this as an example:

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

this should print

Item espresso, cost: 1.5
Item latte, cost: 2.5
Item cappuccino, cost: 3.0
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Thank you! But, why couldn't it just be MENU instead of MENU.items()? – TPAL Feb 02 '23 at 00:21
  • 2
    Iterating over a dictionary will only return its keys (drink names in your case). If you want to access both key and the corresponding value you should iterate over [`.items()`](https://docs.python.org/3/library/stdtypes.html#dict.items) – Selcuk Feb 02 '23 at 00:24