蟒蛇5层树结构的构建

时间:2012-03-27 12:37:30

标签: python tree

我希望减少数据库检索数据的次数。因此,我认为将整个数据放入树中会提高系统的性能,因为我不会经常访问数据库。

我是python的初学者,所以请在创建树结构时提供帮助和建议。

2 个答案:

答案 0 :(得分:1)

您可以使用嵌套的dictionaries。嵌套意味着key:value对的值可以是另一个字典。

<小时/> JerseyMike给出了一个很好的例子,我只想指出他的addItemAttributes函数相当于更简洁

def addItemAttributes(tree, idList):
    (menu, cat, subcat, item, attribs) = idList;

    currDict = tree.setdefault(menu, {})\
        .setdefault(cat, {})\
        .setdefault(subcat, {})\
        .setdefault(item, {})

    for a in attribs:
        currDict[a[0]] = a[1]

...并且您可能希望在try块中包含getItemAttributes,以便您可以处理缺少其中一个键的情况,例如。

try:
    getItemAttributes(...)
except KeyError:
    #key was incorrect, deal with the situation

答案 1 :(得分:0)

我正在将它们放在一起,因为我没有方便的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

我希望这会有所帮助。 :)