在space中将空格分隔的树转换为有用的dict

时间:2010-11-24 20:00:02

标签: python whitespace

我有一个项目的输出(列表),如:

Root
  Branch1
    LeafA
    LeafB
  Branch2
    LeafC
      LeafZ
    LeafD

它们都是两个空格分隔的。 我希望在没有前导空格的情况下构建此列表的逻辑表示,并保留父子关系。

最终可能的结果:

aDict = {
    'Root': null,
    'Branch1': 'Root',
    'LeafA': 'Branch1',
... so on and so forth
}

最终,我想遍历字典并检索Key和parent,以及另一个基于Key的dict中的另一个值。

2 个答案:

答案 0 :(得分:4)

试试这个:

tree = """Root
  Branch1
    LeafA
    LeafB
  Branch2
    LeafC
      LeafZ
    LeafD"""

aDict = {}
iDict = {}
for line in tree.split("\n"):
    key = line.lstrip(" ")
    indent = (len(line) - len(key)) / 2
    if indent == 0:
        aDict[key] = None
    else:
        aDict[key] = iDict[indent - 1]
    iDict[indent] = key

print aDict
# {'LeafD': 'Branch2', 'LeafA': 'Branch1', 'Branch2': 'Root', 'LeafC': 'Branch2', 'LeafB': 'Branch1', 'Branch1': 'Root', 'Root': None, 'LeafZ': 'LeafC'}

答案 1 :(得分:0)

我想这解决了这个问题:

#!/usr/bin/env python

def f(txt):
    stack = []
    ret = {}
    for line in txt.split('\n'):
        a = line.split('  ')
        level = len(a) - 1
        key = a[-1]
        stack = stack[:level]
        ret[key] = stack[-1] if len(stack) > 0 else None
        stack.append(key)
    return ret

print f("""Root
  Branch1
    LeafA
    LeafB
  Branch2
    LeafC
      LeafZ
    LeafD""")

print f("""Root1
  Branch1
    LeafA
      LeftZ
  Branch2
    LeftB
Root2
  Branch3""")

输出:

{'LeafD': 'Branch2', 'LeafA': 'Branch1', 'Branch2': 'Root', 'LeafC': 'Branch2', 'LeafB': 'Branch1', 'Branch1': 'Root', 'Root': None, 'LeafZ': 'LeafC'}
{'LeafA': 'Branch1', 'Branch2': 'Root1', 'Branch1': 'Root1', 'LeftZ': 'LeafA', 'LeftB': 'Branch2', 'Branch3': 'Root2', 'Root1': None, 'Root2': None}