昨日見ておもしろかったので(auto-vivification)

直接元のgistを見ないで再現してみた。再現できていたので理解は合ってた。良かった。

code

## https://en.wikipedia.org/wiki/Autovivification

from collections import defaultdict

def tree():
    return defaultdict(tree)

def tree_as_dict(t):
    if hasattr(t, "__iter__"):
        return {k:tree_as_dict(t[k]) for k in t} 
    else:
        return t

t = tree()
t["x"]["y"]["z"] = 1
t["x"]["y"]["a"] = 2
t["x"]["a"]["b"] = 2
t["x"]["b"]["a"] = 2

print tree_as_dict(t)
# {'x': {'y': {'a': 2, 'z': 1}, 'a': {'b': 2}, 'b': {'a': 2}}}

see also

one-line tree in python ― Gist https://gist.github.com/2012250