Friday, January 10, 2014

loopdefaultdict

Simple idiom for a tree.

>>> import collections
>>>
>>> def loopdefaultdict():
...    return collections.defaultdict(loopdefaultdict)
...
>>> d = loopdefaultdict()
>>> d[1][2][3]
defaultdict(<function loopdefaultdict at 0x02B249B0>, {})
>>> d[1][2][3] = "cat"

Edit: wikipedia has an even better version
http://en.wikipedia.org/wiki/Autovivification#Python
Tree = lambda: defaultdict(Tree)

No comments:

Post a Comment