Creating multilevel dictionary from a list of tuples

78 Views Asked by At

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?

2

There are 2 best solutions below

2
AKX On BEST ANSWER

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).

1
vagitus On

i think you are looking for something like this:

key_value = [('A', 'B'), ('B', 'C'), ('C', 'E'), ('C', 'D'), ('E', 'F')]

def create_dict_tree(parent, key_value):
    child_dict = {}
    for k, v in key_value:
        if k == parent:
            child_dict[v] = create_dict_tree(v, key_value)
    return child_dict if child_dict else {}

parent = 'A'
dict_tree = {parent: create_dict_tree(parent, key_value)}
print(dict_tree)