Storing 'unhashable' types in dictionaries by address
Ed Avis
ed at membled.com
Sun May 25 12:12:54 EDT 2003
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.
Something which would be almost as good is to take the address of a
list or other object, then I could use that as the key of a
dictionary.
Is there any library which can do what I want, either by providing its
own dictionaries which don't require objects to be hashable, or by
letting the programmer get the address of an object?
--
Ed Avis <ed at membled.com>
More information about the Python-list
mailing list