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

Peter Otten __peter__ at web.de
Fri Mar 27 20:37:55 CET 2009


Mudcat wrote:

> 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.

You can use a defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(lambda: "reserved", [(1,2), (2,3)])
>>> d[1]
2
>>> d[2]
3
>>> d[42]
'reserved'

If the keys are successive integers starting at 0 a list is also an option.
It makes setting ranges to a particular value easy:

>>> d = ["reserved"]*2**16
>>> d[10:20] = [42]*10
>>> d[5], d[10], d[15], d[20]
('reserved', 42, 42, 'reserved')

Peter



More information about the Python-list mailing list