Re:Python Tips and Traps
by birken on Monday January 19, 2015 @02:06PM
(#8913428)
[ Parent
| on HN ]
Re:Python Tips and Traps
by jonathanpoulter on Monday January 19, 2015 @02:21PM
(#8913517)
For reference, this is called autovivification.
http://en.wikipedia.org/wiki/Autovivification#Python
Oops, messed this up (too late to edit). Thanks choochootrain for the correction:
>>> NestedDD = lambda: collections.defaultdict(NestedDD)
>>> nested_dd = NestedDD()
>>> nested_dd['a']['b']['c']['d'] = 'hello'
does the proper thing.I don't think that's what they wanted:
>>> nested_dd['d']
'hello'
Re:Python Tips and Traps
by choochootrain on Monday January 19, 2015 @03:57PM
(#8914022)
try
nested_dd = lambda: defaultdict(nested_dd)
Re:Python Tips and Traps
by jamiesonbecker on Monday January 19, 2015 @04:15PM
(#8914117)
Just. Wow.
from collections import defaultdict
defaultobj = lambda: type('defaultobj', (defaultdict,), {
'__getattr__': lambda self, x: self.__getitem__(x),
'__setattr__': lambda self, x, v: self.__setitem__(x, v)
})(defaultobj)
names = defaultobj()
names.mammalia.primates.homo['H. Sapiens'] = 'Human being'
print(names)
The same but also allows dot notation.