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:
First element in each tuple is parent process and second element is the tuple is child process and they should be like {"A": {"B": {} ...
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?
I'd go with this:
The output is
which corresponds to your output (even if the print order is different).