1

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!

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

It works! only a minor difference is that the last else is not needed because the tree node always need to go to the next level. Thank you!
I am sorry. I wrote this code. ideone.com/7JvBub It doesnt work. It says AttributeError: Item instance has no attribute 'get_attr' Which type of objects will work with get_attr?
I thought the get_attr was a user defined function. If you intend to use the built in getattr function, then the syntax is getattr(obj).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.