Reputation: 145
So I have a very big list of a nested dictionary, but I'm gonna use only a small info of them, for the example.
So I'm trying to print this nested dictionary:
MN = {}
count_ = 1
menu_category = "DESSERT"
mi_item = 'Cake'
mi_price = '$5.00'
mi_description = 'Eggs, Sugar'
MN[count_] = {menu_category:{mi_item:{'price':mi_price, 'description':mi_description}}}
MC = ''
for mi_id, mi_cat, mi_it in MN.items():
for mc in mi_cat:
if mc != MC:
print(f'Menu Category: {mc}')
print()
else:
MC = mc
print(f"{mc[mi_it]}: ", end='')
for m_it in mi_it:
print(f"{m_it}: {mi_it[m_it]}", end='\n')
print()
But I'm getting this Error:
Traceback (most recent call last):
File "c:\Users\bilakos\Desktop\PYTHON_PROJECTS\test.py", line 9, in <module>
for mi_id, mi_cat, mi_it in MN.items():
ValueError: not enough values to unpack (expected 3, got 2)
What I'm doing wrong here?
Upvotes: 0
Views: 108
Reputation: 780974
items()
only iterates over the top level of the dictionary, not the nested dictionaries. So you need to write your own nested loop.
MC = ''
for mi_id, mi_cat in MN.items():
for mc, mi in mi_cat.items():
if mc != MC:
print(f'Menu Category: {mc}')
print()
MC = mc
for item_name, item_details in mi.items():
print(f' Item: {item_name}')
print(f' Price: {item_details["price"]}')
print(f' Description: {item_details["description"]}')
print()
The part of the loop that prints the items details shouldn't be in else:
, because you'll skip the first item of a new category.
Also, it seems like MN
should be a list rather than a dictionary, since the order matters (you want all the items in the same category together). Or you should have another level of grouping.
Upvotes: 1