Making a tree out of a 2 column list

martinskou at gmail.com martinskou at gmail.com
Sat Apr 14 12:48:41 EDT 2007


Hope this helps

# list of pairs [child,parent]
list=[[2,131],[6,335],[7,6],[8,9],[10,131],[131,99],[5,10]]

# list with loop
#list=[[2,131],[6,335],[7,6],[8,9],[10,131],[131,99],[5,10],[3,10],
[131,3]]

# put the pairs in a dictionary, for easy retrieval
d={}
for c,p in list:
	# must be able to hold multiple values for each key
	if not(d.has_key(p)):
		d[p]=[c]
	else:
		d[p].append(c)


# function to retrieve children using recursion. max_depth to ensure
termination
def retrieve_recursive(key,result=[],max_depth=10):
	if d.has_key(key) and max_depth>0:
		for i in d[key]:
			result.append(i)
			retrieve_recursive(i,result,max_depth-1)
	return result

print retrieve_recursive(131)




More information about the Python-list mailing list