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)

1 comment:

  1. Save goliath with Vista Print improvement codes! Our markdown codes and riding chaps are gotten enterprisingly to outfit you with the most sharp evaluations for your business;

    ReplyDelete