473,802 Members | 1,996 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Hierarchy - how?

I'd like to know how to make the following string:
food
fruit
red
cherry
yellow
banana
meat
pork
foo
bar
baz
qux

Result in a dictionary like this:
{'food': {'fruit': {'red': 'cherry', 'yellow': 'banana'}, 'meat':
'pork'}, 'foo': {'bar': 'baz', 'qux': {}}}

Or something like that (if you understand). What would be the best way
of doing so? I'm thinking re.finditer might be appropriate, but I'm not
sure. I'd prefer not looping TOO much, since it's actually made using a
loop or two.

Actually, if anyone has a better idea of how to do the entire thing,
that'd be even better:
def hierarchy(data, parent='', level=0, out=''):
for item in which_parent(da ta, parent):
out += ' ' * level + item + '\n'
out = hierarchy(data, item, level + 1, out)

return out

def which_parent(da ta, parent):
return filter(None, [item[1] == parent and item[0] or None for item
in data])

data = (('food', ''),
('fruit', 'food'),
('red', 'fruit'),
('yellow', 'fruit'),
('cherry', 'red'),
('banana', 'yellow'),
('meat', 'food'),
('pork', 'meat'),
('foo', ''),
('bar', 'foo'),
('baz', 'bar'),
('qux', 'foo'))

print hierarchy(data)

-- Keep in mind that I don't want a string, I want a dictionary (but I
can't figure out how to do it).

Apr 30 '06 #1
1 1193
Am Sonntag 30 April 2006 19:26 schrieb veracon:
-- Keep in mind that I don't want a string, I want a dictionary (but I
can't figure out how to do it).


The following code does what you want:
# -*- coding: iso-8859-15 -*-

data = """food
fruit
red
cherry
yellow
banana
meat
pork
foo
bar
baz
qux"""

top = {}
stack = [-1]
items = {-1:top}
for l in data.split("\n" ):
lindent, ldata = len(l[:-len(l.lstrip())].expandtabs()), l.lstrip()
while stack[-1] >= lindent:
del items[stack[-1]]
stack.pop()
items[lindent] = {}
items[stack[-1]][ldata] = items[lindent]
stack.append(li ndent)

print top


Making a function out of it is up to you. ;-)

--- Heiko.
Apr 30 '06 #2

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

Similar topics

8
3484
by: vcardillo | last post by:
Hello all, Okay, I am having some troubles. What I am doing here is dealing with an employee hierarchy that is stored in an array. It looks like this: $employees = array( "user_id" => array( "name", "title", "reports to user id", "start date in the format: mm/dd/yyyy" ) ); How can I display this hierarchy in simple nested <li> tags in the most
1
2292
by: Chris Lasher | last post by:
Hello, I'm trying to write a tool to scrape through some of the Ribosomal Database Project II's (http://rdp.cme.msu.edu/) pages, specifically, through the Hierarchy Browser. (http://rdp.cme.msu.edu/hierarchy/) The Hierarchy Browser is accessed first through a page with a form. There are four fields with several options to be chosen from (Strain, Source, Size, and Taxonomy) and then a submit button labeled "Browse". The HTML of the form is...
0
1414
by: archway | last post by:
Hi, I would like to build a hierarchy of ProductNode objects like so ProductNode ---Product Node ---ProductNode ------ProductNode ------ProductNode ---ProductNode
2
4724
by: Matt | last post by:
Hello, I would like to generate what I call an "overall class hierarchy" in UML automatically derived from my C++ code source. An example of what I seek: http://biz2tek.com/tmp/overall-class-hierarchy-sde (This link may be temporary; email me if you can't get access to it, I
2
1930
by: Yaro | last post by:
Hi All (UDB 8.1 FP8, Win) In my simple test database, I have two tables CREATE TABLE "DB2ADMIN"."AAA" ( "F1" INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, "F2" VARCHAR(10), PRIMARY KEY ("F1") )
4
2877
by: Dave Veeneman | last post by:
I have an object hierarchy that's several layers deep, and I'm puzzling over how to access an object at any point in the hierarchy, solely by its key. The hierarchy is similar to an organizational chart, with a CEO at the top, his/her subordinates in the next layer, their subordinates in the layer below that, and so on. Each person is represented by an Employee object, and Each Employee object has a Subordinates collection property (a...
21
1985
by: Mark Broadbent | last post by:
Consider the following statements //------- Item i = Basket.Items; //indexer is used to return instance of class Item Basket.Items.Remove(); //method on class item is fired item i = new ("Pear"); Basket.Items.Add(item); //------
2
2314
by: Do | last post by:
Hi, I have a database table with the following fields: id, name, parentid. These fields are supposed to create a hierarchy for a list box, an infinite hierarchy Child fields of parent fields should be indented. Root folders have a parentid of zero. Child folders in the hierarchy have parentids that correspond to ids. Here are some sample records of folder:
10
3592
by: John Nagle | last post by:
Here are three network-related exceptions. These were caught by "except" with no exception type, because none of the more specific exceptions matched. This is what a traceback produced: 1. File "D:\Python24\lib\socket.py", line 295, in read data = self._sock.recv(recv_size) timeout: timed out
3
3333
by: krzysztof.konopko | last post by:
Hello! I want to design a class hierarchy with one base abstract class, let's say CBase. I have a predicate that every object in the class hierarchy must have a parent object of type from this class hierarchy but only objects of some of these types can be a parent. Example: class CFruit : public CBase { }; class CBranch : public CBase { };
0
9562
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
10536
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
10285
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
10063
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
9114
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
5494
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4270
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
2
3792
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2966
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.