Hierarchy - how?

Heiko Wundram me+python at modelnine.org
Sun Apr 30 13:49:59 EDT 2006


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.



More information about the Python-list mailing list