Wednesday, 28 August 2013

Is there a way to have a dictionary key be a range?

Is there a way to have a dictionary key be a range?

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?

No comments:

Post a Comment