473,804 Members | 2,257 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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':'Proje ct'},
{'title': 'Verticals', 'parent':'Proje ct'},
{'title': 'Points', 'parent':'Geome try'},
{'title': 'Layers', 'parent':'Geome try'},
{'title': 'Water', 'parent':'Geome try'},
{'title': 'Soiltypes', 'parent':'Soil' }]

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

tree_result_lis t = [
# Project
['Project', ['Geometries','V erticals']],
# 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 2518
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(pare nt)]
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_lis t

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(dic tlist):
helpdict={}
for elem in dictlist:
helpdict.setdef ault(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
3132
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 variable
19
2299
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 class, as in: def walk(self): """old-style recursive tree traversal""" child.do_something for child in childs:
9
2807
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
2220
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, having limited experience with hacking out JavaScript but no serious coding with it. I do have programming experience though. The logic seems fine to me. Is there something I'm missing? <script type="text/javascript"> var out = "";
7
2660
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 the inorder traversal from http://www.python.org/peps/pep-0255.html as an example. def inorder(t): if t: for x in inorder(t.left):
7
567
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
2396
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 process if you want. The problem now is to make a Type list so I can specify more than one node at a time to "attach" a class to. I think I will be able to handle this but I want to run the code by you guys to see there are any major design...
16
4270
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);
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10599
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10347
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10090
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9173
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6863
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.