Re: Hierarchy - how?
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Hierarchy - how?

From: Heiko Wundram <me+python@modelnine.org>
Date: Sun Apr 30 2006 - 19:49:59 CEST

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.
Received on Mon May 1 00:47:37 2006