5 ms·
How would you create that hypothetical recurise defaultdict with defaults of defaultdicts? Is such a construct possible without creating a new defaultdefaultdi
by 3JPLW 12y ago
How would you create that hypothetical recurise defaultdict with defaults of defaultdicts? Is such a construct possible without creating a new defaultdefaultdict class?
- deleted 12y ago[deleted]
- 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.
- heydenberk 12y agoFor what it's worth, I found the "bad" example in addict's documentation[1] to be better than the "good" one. It's explicit about the structure of the data. Also, I found the name and the tagline to be distasteful. [1] https://github.com/mewwts/addict#addict---the-python-dict-thats-better-than-heroin https://github.com/mewwts/addict#addict---the-python-dict-th...
- jamiesonbecker 12y agoThanks for the awesome link and agreed, distasteful. (could be worse.. at least it's not 'pimp my python!') At least you won't forget. pip install addict