I have a python dictionary and I would like to create a tree from it. The dictionary is something like this:
dict_={"2":{'parent': "1"},"1":{'parent': None},"3":{'parent': "2"}}
in this case, the root is "1"
I tried to use treelib library but the problem when I iterate on the dictionary and create a node, its parent isn't created yet. For example, if I want to create a node for "2", its parent("1") isn't created yet, so can not do it. Any idea?
Because Python doesn't implement trees for us, we'll define them using dictionaries. Each node of the tree will be a dictionary that has two keys. The first key is the string "value", which maps to the value in the node.
Use the str() and the literal_eval() Function From the ast Library to Convert a Dictionary to a String and Back in Python. This method can be used if the dictionary's length is not too big. The str() method of Python is used to convert a dictionary to its string representation.
You could do the following, using treelib:
from treelib import Node, Tree
dict_ = {"2": {'parent': "1"}, "1": {'parent': None}, "3": {'parent': "2"}}
added = set()
tree = Tree()
while dict_:
for key, value in dict_.items():
if value['parent'] in added:
tree.create_node(key, key, parent=value['parent'])
added.add(key)
dict_.pop(key)
break
elif value['parent'] is None:
tree.create_node(key, key)
added.add(key)
dict_.pop(key)
break
tree.show()
Output
1
└── 2
└── 3
The idea is to add a node only if the parent is present in the tree or the parent is None
. When the parent is None
add it as root.
You can do the following. First, transform the data structure to a parent-children mapping:
from collections import defaultdict
d = defaultdict(list) # parent: List[children]
for k, v in dict_.items():
d[v['parent']].append(k)
Then, starting with the root
root = d[None][0]
tree = Tree()
tree.create_node(root, root)
Create the tree from the top:
agenda, seen = [root], set([root])
while agenda:
nxt = agenda.pop()
for child in d[nxt]:
tree.create_node(child, child, parent=nxt)
if child not in seen:
agenda.append(child)
seen.add(child)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With