Range as dictionary key in Python
<p>So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary.</p>

<p>I wrote the code bellow, but I cannot get it to work.  Is it even possible?</p>

<pre><code>    stealth_roll = randint(1, 20)
    # select from a dictionary of 4 responses using one of four ranges.
    ## not working.
    stealth_check = {
                    range(1, 6) : 'You are about as stealthy as thunderstorm.',
                    range(6, 11) : 'You tip-toe through the crowd of walkers, while loudly calling them names.',
                    range(11, 16) : 'You are quiet, and deliberate, but still you smell.',
                    range(16, 20) : 'You move like a ninja, but attracting a handful of walkers was inevitable.'
                    }

    print stealth_check[stealth_roll]
</code></pre>

<p>It is possible on Python 3 â and on Python 2 if you use <code>xrange</code> instead of <code>range</code>:</p>

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

<p>However, the way you're trying to use it it won't work. You could iterate over the keys, like this:</p>

<pre><code>for key in stealth_check:
    if stealth_roll in key:
        print stealth_check[key]
        break
</code></pre>

<p>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 <code>dict</code> to work like that automatically:</p>

<pre><code>class RangeDict(dict):
    def __getitem__(self, item):
        if type(item) != range: # or xrange in Python 2
            for key in self:
                if item in key:
                    return self[key]
        else:
            return super().__getitem__(item)

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

python dictionary range