Re:Python Tips and Traps
by 3JPLW on Monday January 19, 2015 @01:45PM
(#8913282)
How would you create that hypothetical recurise defaultdict with defaults of defaultdicts? Is such a construct possible without creating a new defaultdefaultdict class?
[ Parent
| on HN ]
>> nested_dd = collections.defaultdict(lambda: nested_dd)
>> nested_dd['a']['b']['c']['d'] = 'hello'
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.
Re:Python Tips and Traps
by heydenberk on Monday January 19, 2015 @03:25PM
(#8913855)
For 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-th...
Re:Python Tips and Traps
by jamiesonbecker on Monday January 19, 2015 @04:18PM
(#8914137)
Thanks 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