简体   繁体   English

如何使用Python dict动态创建树

[英]How can I dynamically create a tree using Python dict

I'm going to create a tree using python dict without knowing the exact number of levels and nodes before doing it. 我将使用python dict创建一棵树,而在执行之前不知道级别和节点的确切数目。

For example I'm gonna loop many items with 3 attributes: size, color, and weight. 例如,我要循环许多具有3个属性的项目:大小,颜色和重量。 In each loop I do the following things 在每个循环中,我执行以下操作

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...

Finally I get a dict like this 最后我得到这样的字典

item_data == {'L':{
                  'red':{45:[...], 
                         50:[...]}, 
                  'green':{
                         40:[...]}}, 
              'XL':{...}}

But this is not flexible. 但这并不灵活。 For example if I want to add another attribute like 'price'? 例如,如果我要添加另一个属性,例如“价格”? I have to know it and add one more if in the codes above. 我必须知道,如果在上面的代码中再添加一个。

I'm thinking about doing it in the following way, but don't know how to do it in few lines 我正在考虑通过以下方式进行操作,但不知道如何在几行中完成操作

attrs = [item.get_attr()]
for attr in attrs:
    # Create the tree here..

Thanks in advance! 提前致谢!

See if networkx is relevant here. 在这里查看networkx是否相关。 Otherwise, here is a basic version extending your idea of using attr loop (code not tested). 否则,这是一个基本版本,扩展了您使用attr循环的想法(未经测试的代码)。

for item in items:
    tree = item_data
    for i,attr in enumerate(item.get_attr()):
        if attr not in tree.keys():
            if i<len(item.get_attr())-1:
                tree[attr] = {}
            else:
                tree[attr] = []
        else:
            tree = tree[attr]
    # do something to the tree

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM