1

I have a Python list of dictionary in the form e.g.

[{'Parent':'top', 'Child':'obj1', 'Level':0},
 {'Parent':'obj1', 'Child':'obj2', 'Level':1},
 {'Parent':'obj1', 'Child':'obj3', 'Level':1},
 {'Parent':'obj2', 'Child':'obj4', 'Level':2},
 {'Parent':'obj4', 'Child':'obj5', 'Level':3}]

I want to write this out as a nested html list based on the Parent e.g.

  • obj1
    • obj2
      • obj4
        • obj5
    • obj3

How can I do this in a Django template

2
  • 2
    Why are you creating a flat dictionary? What's the "original" information? Commented May 5, 2011 at 10:03
  • Not really a helpful answer. Can you update the question to show the table and the query? I suspect that the query (or model) can be fixed to be properly nested. Commented May 5, 2011 at 10:45

1 Answer 1

3

Quick solution:

def make_list(d):
    def append_children(parent, d):
        children = [[x['Child']] for x in d if x['Parent'] == parent[0]]
        if children:
            parent.append(children)
            for child in children:
                append_children(child, d)

    results = [[x['Child']] for x in d if x['Parent'] == 'top']
    for parent in results:
        append_children(parent, d)

    return results

Pass the list into this function and then apply unordered_list filter to the result. The disadvantage of this method is that <ul> list is created even for one element (<ul><li>elem</li></ul>), but you can alter display as you like with CSS.

If you want clearer HTML you should write a custom tag or filter for that.

Sign up to request clarification or add additional context in comments.

Comments

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.