Range as dictionary key in Python

It is possible on Python 3 — and on Python 2 if you use xrange instead of range:

stealth_check = {
                xrange(1, 6) : 'You are about as stealthy as thunderstorm.', #...
                }

However, the way you’re trying to use it it won’t work. You could iterate over the keys, like this:

for key in stealth_check:
    if stealth_roll in key:
        print stealth_check[key]
        break

Performance of this isn’t nice (O(n)) but if it’s a small dictionary like you showed it’s okay. If you actually want to do that, I’d subclass dict to work like that automatically:

class RangeDict(dict):
    def __getitem__(self, item):
        if not isinstance(item, range): # or xrange in Python 2
            for key in self:
                if item in key:
                    return self[key]
            raise KeyError(item)
        else:
            return super().__getitem__(item) # or super(RangeDict, self) for Python 2

stealth_check = RangeDict({range(1,6): 'thunderstorm', range(6,11): 'tip-toe'})
stealth_roll = 8
print(stealth_check[stealth_roll]) # prints 'tip-toe'

Leave a Comment