因为我手头没有 Python 解释器,所以我将它们放在一起。这里有两个用于填充和读取嵌套字典结构的函数。传递给每个参数的第一个参数是包含所有菜单信息的基本字典。
此函数用于添加字典。这个函数在代码方面可能更有效,但我希望你了解发生了什么。对于每个菜单类别的每个子类别的每个项目,您都需要构造一个要传入的属性列表。
# 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)
从嵌套结构中读取的函数更容易理解:
# 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
我希望这会有所帮助。 :)