Search code examples
pythondefaultdict

Creating multilevel dictionary from a list of tuples


I have list of tuples showing relationship between nodes: key_value = [('A', 'B'), ('B', 'C'), ('C', 'E'), ('C', 'D'), ('E', 'F')]

From this list of tuples, I would like to create a dictionary tree. So that:

  1. First element in each tuple is parent process and second element is the tuple is child process and they should be like {"A": {"B": {} ...

  2. If child process does not appear as parent process in other tuple like 'D' then its value should be empty dictionary {}.

So final output should be:

dict_tree = {'A': {'B': {'C': {'D': {}, 'E': {'F': {}}}}}}

I tried below but not near to solution

from collections import defaultdict
dict_tree = defaultdict(dict)
key_value = [('A', 'B'), ('B', 'C'), ('C', 'E'), ('C', 'D'), ('E', 'F')]

for level, value in key_value:
    dict_tree[level][value] = {}

print(dict_tree)

OUTPUT:

defaultdict(<class 'dict'>, {'A': {'B': {}}, 'B': {'C': {}}, 'C': {'E': {}, 'D': {}}, 'E': {'F': {}}})

How can I approach this further?


Solution

  • I'd go with this:

    key_value = [
        ("A", "B"),
        ("B", "C"),
        ("C", "E"),
        ("C", "D"),
        ("E", "F"),
    ]
    
    dict_tree = {}
    dicts_by_name = {}
    for key, value in key_value:
        target = dicts_by_name.setdefault(key, {})
        if not dict_tree:  # no root yet, so install it
            dict_tree[key] = dicts_by_name[key]
        target[value] = dicts_by_name.setdefault(value, {})
    
    print(dict_tree)
    

    The output is

    {'A': {'B': {'C': {'E': {'F': {}}, 'D': {}}}}}
    

    which corresponds to your output (even if the print order is different).