How to convert python list of tuples into tree?
<p>I have a list of tuples like</p>

<pre><code>list_of_tuples = [(number, name, id, parent_id),
     (number, name, id, parent_id),
    ]
</code></pre>

<p>I am trying to sort it into an ordered structure like:</p>

<pre><code>{
    parent: [(id, name), (id, name)],
    parent: {parent: [(id, name)]
{
</code></pre>

<p>So, any node could have a parent and/or children
I tried with:</p>

<pre><code>tree = defaultdict(lambda: [None, ()])
ancestors = set([item[3] for item in list_of_tuples])

for items in list_of_tuples:
    children_root = {}
    descendants = []
    number, name, id, parent = items
    if parent is None:
        tree[id] = [(id, name)]
    elif parent:
        if parent not in tree.keys():
            node = tree.get(parent)
            node.append((id, name))
        children = (id, name)
        tree[parent].append(children)
</code></pre>

<p>But I'm losing deep hierarchy when a node has both a parent and children</p>

<p>How do I make the ordering work correctly?</p>