Hierarchy - how?

V

veracon

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(data, parent):
out += ' ' * level + item + '\n'
out = hierarchy(data, item, level + 1, out)

return out

def which_parent(data, 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).
 
H

Heiko Wundram

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(lindent)

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

--- Heiko.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,511
Members
48,203
Latest member
LillianaFr

Latest Threads

Top