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

.



Relevant Pages

  • Re: Joe Celkos Nested sets
    ... I recreate the nested set representation from scratch when I ... Private Const errParentTable As String = "Parent Table in error." ... Parent Table has null and so can't be use for primary key." ...
    (microsoft.public.access.queries)
  • RE: Re-run a Query Based on Previous Results
    ... Function fnProgenitor(Fsbill As String, ... Dim rs As DAO.Recordset ... The value for ID is the first Parent in Fsbill. ...
    (microsoft.public.access.queries)
  • Re: Treeview
    ... I'll have a B please Bob. ... > Public DirectoryPath as string ... > Dim BaseFilePath as FilePath 'the root object> 'open a stream from the file and read each line into a local variable. ... > 'now get the parent address which should be the same for every line ...
    (microsoft.public.dotnet.languages.vb)
  • RE: Re-run a Query Based on Previous Results
    ... When you changed the datatype declaration on lngMyID to string, ... Let me rewrite fnProgenitor as I think it should probably read for your ... Dim rs As DAO.Recordset ... The value for ID is the first Parent in Fsbill. ...
    (microsoft.public.access.queries)
  • RE: Re-run a Query Based on Previous Results
    ... When you changed the datatype declaration on lngMyID to string, ... Let me rewrite fnProgenitor as I think it should probably read for your ... Dim rs As DAO.Recordset ... The value for ID is the first Parent in Fsbill. ...
    (microsoft.public.access.queries)