473,385 Members | 1,409 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Recursive tree list from dictionary

Hi. I am wanting to create a tree list result structure from a
dictionary to categorize results. The dictionary contains elements that
identify its parent. The levels of categorization is not fixed, so there
is a need for the code to be recursive to drill down to the lowest
level. I have contrived a small source and result list to illustrate:

source_list =[
{'title': 'Project', 'parent':'root'},
{'title': 'Geometry', 'parent':'root'},
{'title': 'Soil', 'parent':'root'},
{'title': 'Geometries', 'parent':'Project'},
{'title': 'Verticals', 'parent':'Project'},
{'title': 'Points', 'parent':'Geometry'},
{'title': 'Layers', 'parent':'Geometry'},
{'title': 'Water', 'parent':'Geometry'},
{'title': 'Soiltypes', 'parent':'Soil'}]

What I want to do is a tree list like this:

tree_result_list = [
# Project
['Project', ['Geometries','Verticals']],
# Geometry
['Geometry', ['Points', 'Layers', 'Water']],
# Soil
['Soil', ['Soiltypes']]
]

I have not been successful and am hoping someone can
advise a solution to accomplish this. Many thanks.

Regards
David
Jan 14 '06 #1
2 2490
This isn't much tested, so don't trust it much, and I hope it's not
overkill.
You can find Graph here:
http://sourceforge.net/projects/pynetwork/
With this you can plot the tree, if you want:
g.springCoords(); g.plot2d()

Bear hugs,
bearophile
def scan(g, parent):
subs = [scan(g, sub) for sub in g.outNodes(parent)]
if subs:
return [parent, subs]
else:
return parent

from graph import Graph
g = Graph()
for d in source_list:
g.addArc(d["parent"], d["title"])
roots = [n for n in g if not g.inNodes(n)]
assert len(roots) == 1 # optional
result = scan(g, roots[0])[1]
print result, "\n\n", tree_result_list

Jan 14 '06 #2
Il Sat, 14 Jan 2006 13:52:43 -0400, David Pratt ha scritto:
source_list =[


I don't understand what you mean by saying that 'levels of categorization
is not fixed', are there more than two keys in any dictionary?

Basically, thus, you have a list of dictionaries and you want to get a list
of lists, right? You haven't specified what order would you like the list
to be sorted, though. Maybe you would benefit from use and ordered
dictionary implementation like orderedDict, but such behaviour can be
created anyway. I would use a kind of 'helper dictionary' to map the list
position to the root element:

def convertList(dictlist):
helpdict={}
for elem in dictlist:
helpdict.setdefault(elem['parent'],[])
helpdict[elem['parent']].append(elem['title'])

return [k,v for k,v in helpdict.items() if k!='root']

--
Alan Franzoni <al***************@gmail.com>
-
Togli .xyz dalla mia email per contattarmi.
To contact me, remove .xyz from my email address.
-
GPG Key Fingerprint:
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E
Jan 14 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: replace-this-with-my-name | last post by:
Hi. How do I return a string containing an entire menu-tree from a recursive function? Here is my current recursive function: function page_tree( $_i ){ //Call global mysql connection...
19
by: Carlos Ribeiro | last post by:
Hello all, Here I am using some deeply nested, tree-like data structures. In some situations I need to traverse the tree; the old-style way to do it is to write a recursive method on the node...
9
by: JP SIngh | last post by:
Hi All I am trying to write a recursive function to list the managers and his employees in a tree like sctructure Manager 1 Emp1 Emp1.1 Emp 1.2 Emp 2
8
by: Ryan Stewart | last post by:
Putting the following code in a page seems to make it go into an infinite loop unless you give it a very simple node to work with. Either that or it's very very slow. I'm somewhat new to this,...
7
by: aurora | last post by:
I love generator and I use it a lot. Lately I've been writing some recursive generator to traverse tree structures. After taking closer look I have some concern on its performance. Let's take...
7
by: Jon Slaughter | last post by:
#pragma once #include <vector> class empty_class { }; template <int _I, int _J, class _element, class _property> class RDES_T {
1
by: Jon Slaughter | last post by:
I've managed to put together a template class that basicaly creates a recursive tree that lets you easily specify the "base" class of that tree and and ending notes and lets you stop the recursive...
16
by: colin | last post by:
Hi, is it possible to have a recursive GetEnumerator for traversing a tree structure ? public IEnumerator<DTypeGetEnumerator() { return GetEnumerator(root);
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.