Mapping with continguous ranges of keys

D'Arcy Cain darcy at
Thu Dec 15 12:24:51 EST 2016

On 2016-12-15 12:06 PM, Steve D'Aprano wrote:
> I have about a million or two keys, with a few hundred or perhaps a few
> thousand distinct values. The size of each contiguous group of keys with
> the same value can vary from 1 to perhaps a hundred or so.

There isn't enough info in your post to be sure but if those values are 
constant then you might be able to subclass dict and write a new 
__getitem__ that checks for specific ranges and calls the superclass 
only if not in the known ranges.  For example:

class MyDict(dict):
   def __getitem__(self, key):
     if isinstance(key, int) and key >= 1 and key <= 100:
       return "foo"
     return dict.__getitem__(self, key)

Obviously that middle section can be as complex as you need.

D'Arcy J.M. Cain
System Administrator, Vex.Net
http://www.Vex.Net/ IM:darcy at Vex.Net
VoIP: sip:darcy at Vex.Net

More information about the Python-list mailing list