3 ms·
>> nested_dd = collections.defaultdict(lambda: nested_dd) >> nested_dd['a']['b']['c']['d'] = 'hello'
by birken 12y ago
>> nested_dd = collections.defaultdict(lambda: nested_dd)
>> nested_dd['a']['b']['c']['d'] = 'hello'
- jonathanpoulter 12y agoFor reference, this is called autovivification. http://en.wikipedia.org/wiki/Autovivification#Python http://en.wikipedia.org/wiki/Autovivification#Python
- rnhmjoj 12y agofrom 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.
- bdr 12y agoI don't think that's what they wanted: >>> nested_dd['d'] 'hello'
- choochootrain 12y agotry nested_dd = lambda: defaultdict(nested_dd)
- jamiesonbecker 12y agoJust. Wow.
- birken 12y agoOops, 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.