Autovivify in Python

Autovivify is simply fancy word for the behavior of creating a dictionary key-value automatically the moment an element is accessed. Python throws an error if the kv-pair was not already created.

Perl hashes/dictionaries are auto-vivified by default, not so for Python, which could be annoying, because you have to do additional checks thus breaking the normal flow of coding.

Here is how you make a auto vivifying Python dictionary and at the same time quick way to create a Tree structure :

from collections import defaultdict
from pprint import pprint

def Tree():
    return defaultdict(Tree)

tree = Tree()
tree['mammal']['ape']['chimp'] = 'bobo'

pprint(tree,indent=2,compact=True)

-----

defaultdict(...,
  { 'mammal': defaultdict(...,
    { 'ape': defaultdict(...,
      { 'chimp': 'bobo'})})})

Even better, if you want cleaner print :

from collections import defaultdict
from pprint import pprint

def Tree(): return DD(Tree)

class DD(defaultdict):
    __repr__ = dict.__repr__

tree = Tree()
tree['mammal']['ape']['chimp'] = 'bobo'

pprint(tree,indent=2,compact=True)

------

{'mammal': {'ape': {'chimp': 'bobo'}}}