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>

<p>I propose to represent the tree nodes as tuples ((id, name), dict_of_children).</p>

<pre><code>list_of_tuples = [(1, 'name1', 1, None),
     (2, 'name2', 2, 1),
     (3, 'name3', 3, 1),
     (4, 'name4', 4, 2),
     (5, 'name5', 5, 2),
     (6, 'name5', 6, None),
     (7, 'name5', 7, 6),
    ]

def build_tree(list_of_tuples):
    """
    &gt;&gt;&gt; import pprint
    &gt;&gt;&gt; pprint.pprint(build_tree(list_of_tuples))
    {1: ((1, 'name1'),
         {2: ((2, 'name2'), {4: ((4, 'name4'), {}), 5: ((5, 'name5'), {})}),
          3: ((3, 'name3'), {})}),
     6: ((6, 'name5'), {7: ((7, 'name5'), {})})}
    """
    all_nodes = {n[2]:((n[2], n[1]), {}) for n in list_of_tuples}
    root = {}
    for item in list_of_tuples:
        number, name, id, parent = item
        if parent is not None:
            all_nodes[parent][1][id] = all_nodes[id]
        else:
            root[id] = all_nodes[id]
    return root
</code></pre>

python algorithm tree binary-search-tree