Any way to use a range as a key in a dictionary?

Daniel Fetchinson fetchinson at googlemail.com
Thu Mar 26 22:51:04 CET 2009


> I would like to use a dictionary to store byte table information to
> decode some binary data. The actual number of entries won't be that
> large, at most 10. That leaves the other 65525 entries as 'reserved'
> or 'other' but still need to be somehow accounted for when
> referenced.
>
> So there are a couple of ways to do this that I've seen. I can loop
> that many times and create a huge dictionary. This isn't a good idea.
> I can just assume if a key isn't there that it's not relevant. That's
> a better idea.
>
> However I wondered if there was a way to simply use a range as a key
> reference somehow. I played around with some options with no success.
> Or maybe there was another way to do this with another data type that
> I haven't thought about.

Ranges are lists and lists are unhashable. But tuples are hashable so
if you convert your lists into tuples, that will work:

>>> x = dict( )
>>> x[range(10)]='hello'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> x[tuple(range(10))]='hello'
>>> x[tuple(range(10))]
'hello'
>>>



-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown



More information about the Python-list mailing list