Re: Hierarchy - how?



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



Relevant Pages

  • Re: Creating "multiple" rows manually with SELECT
    ... (SELECT 'Apple' AS FRUIT ... SELECT 'Banana' AS FRUIT ... SELECT 'Cherry' AS FRUIT) A ...
    (microsoft.public.sqlserver.programming)
  • Re: charting how many widgets over time
    ... 4/29/06 12:20 AM banana ... 4/29/06 3:36 AM apple ... 4/29/06 10:05 AM cherry ... I selected one cell in the range and created a pivot table. ...
    (microsoft.public.excel.charting)
  • Re: Thomas Covenant series
    ... the color of the fruit is not merely a mix ... banana, monkey imagine banana, monkey imagine /eating/ banana, yum", ... the exact shapes and colors. ...
    (rec.arts.sf.composition)
  • Re: Tomatoes
    ... All four of the cherry tomatoes are covered with fruit. ... The one that might be a Pink Russian is still blossoming but I don't ...
    (rec.crafts.textiles.yarn)
  • Re: how detect english subject and predicate in a sentence
    ...  Both readings are correct. ... fruit, but I would imagine that a banana with its elongated, curved form ... flies rather differently than an apple or a coconut. ...
    (comp.lang.perl.misc)