You are iterating over cost as well. Try this:
#level one of the dictionary
for drink, data in MENU.items():
#this should print the drinks and cost
print(drink, data["cost"])
#this should print the ingredients
for ingredient in data["ingredients"].items():
print(ingredient)
Answer from Bharel on Stack OverflowYou are iterating over cost as well. Try this:
#level one of the dictionary
for drink, data in MENU.items():
#this should print the drinks and cost
print(drink, data["cost"])
#this should print the ingredients
for ingredient in data["ingredients"].items():
print(ingredient)
As Bharel suggested, if you just iterate the dict MENU python will by default iterate only the keys - this is why the code works if you just run:
for drink in MENU:
#this should print the drinks and cost
print(drink)
But it will raise an exception when you try the second for loop, because you are not iterating the values, to iterate both values and keys use MENU.items() as Bharel suggested.
for key, value in MENU.items():
#this should print the drinks and cost
print(key, value["cost"])
#this should print the ingredients
for key_i, value_i in value["ingredients"].items():
print(key_i, value_i)
The order of the loops has to be reversed.
This is what you're looking for:
D = {f'{ko}_{ki}_{i}': someFunc(ko, ki, i) for ko, vo in d.items() for ki, vi in vo.items() for i in range(vi) }
The for clauses in the list comprehension should appear in the same order as in the equivalent for-loop code. The only thing that "moves" is that the innermost assignment is replaced by an expression at the beginning.
Please see https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ for details.