Python hash
Paddy
paddy3118 at googlemail.com
Sat Aug 18 08:41:20 EDT 2007
On Aug 18, 12:30 pm, Nick Craig-Wood <n... at craig-wood.com> wrote:
> 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 <n... at craig-wood.com> --http://www.craig-wood.com/nick
Nick,
I thought I'd save your hash implementation away in my bag of tricks:
# File: autovivifying_dict.py
from collections import defaultdict
class hash(defaultdict):
""" Used like a dict except sub-dicts automagically created as
needed
Based on: http://groups.google.com/group/comp.lang.python/msg/f334fbdafe4afa37
>>> D=hash()
>>> D[1][2][3][4]=5
>>> D[1][4][5]=6
>>> D
hash({1: hash({2: hash({3: hash({4: 5})}), 4: hash({5: 6})})})
>>> hash({1: hash({2: hash({3: hash({4: 5})}), 4: hash({7: 8})})})
hash({1: hash({2: hash({3: hash({4: 5})}), 4: hash({7: 8})})})
>>>
"""
def __init__(self, *a, **b):
defaultdict.__init__(self, hash, *a, **b)
def __repr__(self):
return "hash(%s)" % (repr(dict(self)),)
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
- Paddy.
More information about the Python-list
mailing list