public
Last active

Python autovivicating tree with parent reference (variation of the one-line tree)

  • Download Gist
gistfile1.md
Markdown

I was reading the gist @https://gist.github.com/2012250

I found the autovivification functionality of it pretty cool. If only I could have a parent reference...

Obviously this was not going to be a one-line tree. But that wasn't the goal

A simple variant:

from collections import defaultdict
class Tree(defaultdict):
    def initFun(self):
        return Tree(self)
    def __init__(self, parent=None):
        self.parent = parent
        defaultdict.__init__(self, self.initFun)


a = Tree()
a['1']['2'] = 3
a['1']['3']['4'] = 4
a['1']['3'].parent['2']
>>> 3

UPDATE Rhomboid suggested this solution on reddit

from collections import defaultdict

class Tree(defaultdict):
    def __init__(self, parent=None):
        self.parent = parent
        defaultdict.__init__(self, lambda: Tree(self))

And a more elaborate variant which can take in Json or other dicts

from collections import default
from json import loads, dumps
class Tree(defaultdict):
    def __init__(self, inp=None, parent=None):
        self.parent = parent
        defaultdict.__init__(self, lambda: Tree(None, self))
        if inp is not None:
            if isinstance(inp, basestring):
                self.update(loads(inp))
            else:
                self.update(inp)

    def __str__(self, *args, **kwargs):
        return dumps(self, sort_keys=True, indent=4)l


if __name__ == "__main__":
    a = Tree()
    a['1']['2'] = 3
    a['1']['3']['4'] = 4
    a['1']['3'].parent['2']
    print a
    b = Tree({"1": 1, "2": {"1": 3}})
    print b
    c = Tree('{"1": 1, "2": {"1": 3}}')
    print c

a:

{
    "1": {
        "3": {
            "4": 4
        },
        "2": 3
    }
}

b:

{
    "1": 1,
    "2": {
        "1": 3
    }
}

c:

{
    "1": 1,
    "2": {
        "1": 3
    }
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.