Storing 'unhashable' types in dictionaries by address
Mel Wilson
mwilson at the-wire.com
Sun May 25 13:30:38 EDT 2003
In article <l1u1bjgg3d.fsf at budvar.future-i.net>,
Ed Avis <ed at membled.com> wrote:
>A dictionary requires that its key type be hashable. This means you
>cannot use lists as keys of a dictionary. Is there any way round
>this?
>
>I would like to store some 'extra' information associated with some
>lists, but do so outside the lists themselves. For example this is
>what I would like to write:
>
>l0 = ['strawberry']
>l1 = ['mint', 'choc']
>l2 = ['vanilla', 'liver']
>
># This dictionary stores some extra comments on each flavour.
>d = {}
>d[l0] = 'yum'
>d[l1] = 'so-so'
>d[l2] = 'ugh'
>
>print d[l0] # prints 'yum'
>l0.append(55)
>print d[l0] # still prints 'yum', since it's the same list
>
># Now I construct a new list which, although it contains the same
># strings as l1, is a different object. This is just to demonstrate
># that d indexes by 'is' rather than by ==.
>#
>new_list = ['mint', 'choc']
>print new_list in d.keys() # prints 0, or false
>
>
>I hope the intent is clear - I want to look up by object identity and
>not by the contents of the list.
Just store and look up the lists by object identity:
d[id(l0)] = 'yum'
print d[id(l0)]
and so on.
Regards. Mel.
More information about the Python-list
mailing list