简体   繁体   中英

Saving a Tree data structure as a dict in Python

I came across a post called Printing a Tree Data Structure in Python and I like the ability to print the tree traversal.

What I would like is to capture the output as a dictionary instead. This is my print code:

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

Which prints something like this:

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

I have no clue where to even start.

Here's a simple unoptimized version to give you some clues about where to start:

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

Output:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM