License Public Domain
Lines 19
Permissions
Viewable by Everyone
Editable by All Siafoo Users
Hide
Easily highlight source code for your blog with our Syntax Highlighter. Join Siafoo Now or Learn More

Creates a dictionary tree from file Atom Feed 0

In Brief Creates a tree of dictionaries from a file defined by treeChar. Basically this is handy if you want to write out a tree in a plain text file and then convert it to a dictionary set in python. This can be modified to create more complex nodes than just raw text.... more
# 's
 1def makeTree(root,lines,depth):
2 treeChar = "\t"
3 if ( len(lines) == 0 ):
4 return root
5 looping = True
6 while( looping ):
7 nextLine = lines[0]
8 nodeName = nextLine.strip()
9 nodeDepth = nextLine.count(treeChar)
10 if ( nodeDepth == depth): #Node is at current depth, make subtree
11 lines = lines[1:]
12 root[nodeName] = makeTree({},lines,depth+1)
13 elif ( nodeDepth > depth ): #Chomp nodes below my depth
14 lines = lines[1:]
15 else: #return out because I'm in over my head (the next line has a depth shallower than me)
16 break
17 if ( len(lines) == 0 ):
18 looping = False
19 return root

Creates a tree of dictionaries from a file defined by treeChar. Basically this is handy if you want to write out a tree in a plain text file and then convert it to a dictionary set in python. This can be modified to create more complex nodes than just raw text.

a
b
c d
e
f
g
h
i
j
k
l
m
n
o
p
q

will come out as: {'a': {'k': {'l': {}}, 'b': {'c': {}, 'd': {}}, 'e': {'f': {}}, 'g': {'h': {'i': {'j': {}}}}, 'n': {'o': {'p': {'q': {}}}}}}