'Accessing Nested Dictionary 3 levels deep Python
After my for loop successfully returns the keys of my first set of nested dictionaries. I am getting this error:
for item in MENU[drink][ingredient_list]:
TypeError: 'float' object is not iterable
I need to get access to all of the key-value pairs so that I can perform operations on them, but this code gets stuck at 'espresso'.
#3 levels deep nested dictionary
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,
}
}
#level one of the dictionary
for drink in MENU:
#this should print the drinks and cost
print(drink)
#this should print the ingredients
for ingredient_list in MENU[drink]:
print(ingredient_list)
for item in MENU[drink][ingredient_list]:
print(item)
Solution 1:[1]
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)
Solution 2:[2]
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)
Solution 3:[3]
Your dictionary is not a complete 3 level one. It has just 2 complete levels. For example MENU['espresso']['cost'] is equal to 1.5, so you can not iterate on it.
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": {
"normal": 1.5,
"vip": 4.5,
}
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": {
"normal": 2.5,
"vip": 6.5,
}
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": {
"normal": 3,
"vip": 4.1,
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bharel |
| Solution 2 | Karl Knechtel |
| Solution 3 |
