Skip to content

Instantly share code, notes, and snippets.

@obeleh
Last active March 10, 2021 09:47
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save obeleh/4451005 to your computer and use it in GitHub Desktop.
Save obeleh/4451005 to your computer and use it in GitHub Desktop.
Python autovivicating tree with parent reference (variation of the one-line tree)

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
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment