Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have a dictionary key be a range? [duplicate]

Forgive me if this is obvious, but I'm very, very new to Python. I've found ways to get multiple keys from a dictionary, but that's not what I'm trying to do.

Basically I'm looking for something like this:

my_dict = { "1-10" : "foo",
            "11-20" : "bar",
            # ...
            "91-100" : "baz" }

... but where the keys aren't actually strings and any number in that given range maps to the value. So for example, my_dict[9] ought to return foo, just as my_dict[3] should. I thought of using an explicit array, like the following, but it didn't work:

my_dict = { [1, 2, 3, ..., 10] : "foo",

I'm unsure if this is even a valid use-case for a dictionary, or if there is another data structure I should be using. But Python has a way of always surprising me. So does anyone know Python magic to make this work?

like image 253
asteri Avatar asked Oct 17 '25 13:10

asteri


1 Answers

I must say I've never had any need to do anything like this, and there's certainly no built-in datastructure for it. (If you know anything about hashes, you'll understand why a dict can't work that way.)

One possibility would be not to use a dict at all, but have separate lists of keys and values, with the key list being the beginning of each "range". So:

keys = [0, 10, 20, 30]
values = ['foo', 'bar', 'baz', 'quux']

And now you can use bisect to find the relevant key:

import bisect
pos = bisect.bisect_left(keys, 12)
value = values[pos-1]
like image 113
Daniel Roseman Avatar answered Oct 19 '25 02:10

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!