在Python中将树数据结构保存为dict

时间:2018-03-09 03:23:53

标签: python dictionary printing tree output

我遇到了一个名为Printing a Tree Data Structure in Python的帖子,我喜欢打印树遍历的功能。

我想要的是将输出捕获为字典。这是我的打印代码:

def print(self, level=0):
    print('{}{}'.format(' '*4*level, self.node_id))
    for child in self.children:
        child.print(level=level+1)

打印出类似这样的内容:

'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

我不知道哪里可以开始。

1 个答案:

答案 0 :(得分:0)

这是一个简单的未经优化的版本,可以为您提供一些有关从哪里开始的线索:

from itertools import takewhile
import json


class node(object):

    def __init__(self, value, children=[]):
        self.value = value
        self.children = children

    def __str__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__str__(level+1)
        return ret

    def __repr__(self):
        return '<tree node representation>'


def build_tree(lines):
    sep = '\t'
    lst, res = [], []
    for line in iter(lines):
        if not line.strip():
            continue
        indent = len(list(takewhile(sep.__eq__, line)))
        lst[indent:] = [line.lstrip()]
        res.append(sep.join(lst[:]))

    tree = {}
    for item in res:
        t = tree
        for part in item.split(sep):
            t = t.setdefault(part, {})
    return tree

if __name__ == "__main__":
    root = node('grandmother')
    root.children = [node('daughter'), node('son')]
    root.children[0].children = [node('granddaughter'), node('grandson')]
    root.children[1].children = [node('granddaughter'), node('grandson')]
    print('text'.center(80, '='))
    source = str(root)
    print(source)
    print('tree'.center(80, '='))
    print(json.dumps(build_tree(source.split("\n")), indent=4))

输出:

======================================text======================================
'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

======================================tree======================================
{
    "'grandmother'": {
        "'daughter'": {
            "'granddaughter'": {},
            "'grandson'": {}
        },
        "'son'": {
            "'granddaughter'": {},
            "'grandson'": {}
        }
    }
}