Skip to content

Instantly share code, notes, and snippets.

@akdasa
Created October 6, 2019 14:23
Show Gist options
  • Save akdasa/44ef8262e3abd21b2b492cd7f6a8cfa6 to your computer and use it in GitHub Desktop.
Save akdasa/44ef8262e3abd21b2b492cd7f6a8cfa6 to your computer and use it in GitHub Desktop.
Load python dictionary as tree
class Node:
def __init__(self, title: str, parent: "Node" = None):
self.title = title
self.parent = parent
self.children = []
# append self as children of a parent
if parent:
self.parent.children.append(self)
def __repr__(self):
return self.title
data = {
'Location':[
{
'Vrindavan':[
'Temple'
]
}
],
'Persons':[
'Krishna-lila',
'Goura-lila'
],
'Story':[
{
'Krishna-lila':[
'Demons',
'Devotees'
]
},
'Goura-lila',
'Prabhupada'
]
}
def build_tree(node, root):
if isinstance(node, str):
child_node = Node(node, root)
if isinstance(node, list):
for i in node:
build_tree(i, root)
if isinstance(node, dict):
for k, v in node.items():
child_node = Node(k, root)
build_tree(v, child_node)
root_node = Node("Root")
build_tree(data, root_node)
def render_tree(node, level = 0):
print(" " * level * 2, node.title)
for child in node.children:
render_tree(child, level+1)
render_tree(root_node)
Root
Location
Vrindavan
Temple
Persons
Krishna-lila
Goura-lila
Story
Krishna-lila
Demons
Devotees
Goura-lila
Prabhupada
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment