How to say $a=$b->{"A"} ||={} in Python?
Nick Craig-Wood
nick at craig-wood.com
Sat Aug 18 07:30:05 EDT 2007
Paul McGuire <ptmcg at austin.rr.com> wrote:
> Carl Banks' post using defaultdict is the correct solution. The
> raison d'etre for defaultdict, and the reason that it is the solution
> to the OP's question, is that instead of creating a just-in-case
> default value every time, the defaultdict itself is constructed with a
> factory method of some kind (in practice, it appears that this factory
> method is usually the list or dict class constructor). If a reference
> to the defaultdict gives a not-yet-existing key, then the factory
> method is called to construct the new value, that value is stored in
> the dict with the given key, and the value is passed back to the
> caller. No instances are created unless they are truly required for
> initializing an entry for a never-before-seen key.
I think that if you truly want to emulate a perl hash then you would
want this which does the above but recursively.
from collections import defaultdict
class hash(defaultdict):
def __init__(self):
defaultdict.__init__(self, hash)
D=hash()
D[1][2][3][4]=5
D[1][4][5]=6
print D
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list