Hierarchy - how?

veracon veracon at gmail.com
Sun Apr 30 13:26:36 EDT 2006


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




More information about the Python-list mailing list