我将使用 python dict 创建一棵树,但在执行之前不知道确切的级别和节点数。
例如,我将循环许多具有 3 个属性的项目:大小、颜色和重量。在每个循环中,我执行以下操作
item_data = {}
for item in items:
    size, color, weight = item.get_attr()
    if size not in item_data:
        item_data[size] = {}
    if color not in item_data[size]:
        item_data[size][color] = {}
    if weight not in item_data[size][color]:
        item_data[size][color][weight] = []
    # Do something to the tree...
最后我得到一个这样的字典
item_data == {'L':{
                  'red':{45:[...], 
                         50:[...]}, 
                  'green':{
                         40:[...]}}, 
              'XL':{...}}
但这并不灵活。例如,如果我想添加另一个属性,如“价格”?如果在上面的代码中,我必须知道它并添加一个。
我正在考虑通过以下方式进行操作,但不知道如何在几行中做到这一点
attrs = [item.get_attr()]
for attr in attrs:
    # Create the tree here..
提前致谢!