I'm putting this together on the fly since I don't have my Python interpreter handy. Here are two functions for populating and reading from the nested dictionary structures. The first parameter passed to each is the base dictionary that will hold all of your menu information.
This function is used to add to the dictionaries. This function can be probably be more efficient, code-wise, but I wanted you to understand what was going on. For each item of each subcategory of each category of menu, you will need to construct a list of the attributes to pass in.
# idList is a tuple consisting of the following elements:
# menu: string - menu name
# cat: string - category name
# subcat: string - subcategory name
# item: string - item name
# attribs: list - a list of the attributes tied to this item in the form of
# [('Price', '7.95'),('ContainsPeanuts', 'Yes'),('Vegan', 'No'),...].
# You can do the attribs another way, this was convenient for
# the example.
def addItemAttributes(tree, idList):
(menu, cat, subcat, item, attribs) = idList;
if not tree.has_key(menu): # if the menu does not exist...
tree[menu] = {} # Create a new dictionary for this menu
currDict = tree[menu] # currDict now holds the menu dictionary
if not currDict.has_key(cat): # if the category does not exist...
currDict[cat] = {} # Create a new dictionary for this category
currDict = currDict[cat] # currDict now holds the category dictionary
if not currDict.has_key(subcat): # if the subcategory does not exist...
currDict[subcat] = {} # Create a new dictionary for this subcategory
currDict = currDict[subcat] # currDict now holds the subcategory dictionary
if not currDict.has_key(item): # if the category does not exist...
currDict[item] = {} # Create a new dictionary for this category
currDict = currDict[item] # currDict now holds the category dictionary
for a in attribs
currDict[a(0)] = a(1)
The function to read from the nested structure is easier to follow:
# Understand that if any of the vaules passed to the following function
# have not been loaded, you will get an error. This is the quick and
# dirty way. Thank you to Janne for jarring my mind to the try/except.
def getItemAttributes(tree, menu, cat, subcat, item):
try:
return tree[menu][cat][subcat][item].items()
except KeyError:
# take care of missing keys
I hope this helps. :)