4 ms·
In Perl, this is called autovivification: https://en.wikipedia.org/wiki/Autovivification https://en.wikipedia.org/wiki/Autovivification I've wanted something l
by zbuc 14y ago
In Perl, this is called autovivification: https://en.wikipedia.org/wiki/Autovivification https://en.wikipedia.org/wiki/Autovivification
I've wanted something like that in Python at different times... thanks!
edit: Ha! The Wiki article even has basically the same code:
def hash(): return defaultdict(hash)
- kilovoltaire 14y agowow thanks i was actually really curious if there was a name for this sort of thing! added a note about it to the gist. i wonder whether it will be made part of more languages as JSON-esque nested objects proliferate in our code and minds.
- irahul 14y ago> I've wanted something like that in Python at different times... thanks! Python's auto-vivification doens't allow Perl's hap hazard auto-vivification. Perl allows you to say: my $foo = {}; $foo->{'blah'}[0]->{'bar'}++; And after this statement, $foo will refer a hash which has the structure as accessed in the statement. I don't think this can be done for a generalized case in Python. Whether I want is a totally different question.
- jrockway 14y agoWhy is this haphazard? If you don't want reads to change your data structure shape in a well-defined manner, use 'exists' or make an immutable hash with Hash::Util.
- tathagatadg 14y agoI always use http://stackoverflow.com/a/651879/276569 http://stackoverflow.com/a/651879/276569