简体   繁体   中英

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.

For example I'm gonna loop many items with 3 attributes: size, color, and weight. 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. Otherwise, here is a basic version extending your idea of using attr loop (code not tested).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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