Created
October 6, 2019 14:23
-
-
Save akdasa/44ef8262e3abd21b2b492cd7f6a8cfa6 to your computer and use it in GitHub Desktop.
Load python dictionary as tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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