Nick Coghlan wrote:
For a 'mutable key' to make sense, the following:

lst = []
dct = {l: "Hi!"}
print dct[[]]
print dct[lst]
lst.append(1)
print dct[[1]]
print dct[lst]

Should print:
Hi
Hi
Hi
Hi

And here's an implementation that does so:

py> class sillydict(dict):
...     def __getitem__(self, key):
...         items = self.items()
...         self.clear()
...         self.update(items)
...         return super(sillydict, self).__getitem__(key)
...
py> class sillylist(list):
...     def __hash__(self):
...         return hash(tuple(self))
...
py> lst = sillylist([])
py> dct = sillydict({lst: "Hi!"})
py> print dct[sillylist([])]
Hi!
py> print dct[lst]
Hi!
py> lst.append(1)
py> print dct[sillylist([1])]
Hi!
py> print dct[lst]
Hi!

Of course, as noted by the classes themselves, they're silly. ;) But as long as you don't mind rehashing the dict each time the dict is accessed ;) you can get sane behavior even in the presence of mutable keys.

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to