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


forgive me if obvious, i'm very, new python. i've found ways multiple keys dictionary, that's not i'm trying do.

basically i'm looking this:

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

... keys aren't strings , number in given range maps value. example, my_dict[9] ought return foo, my_dict[3] should. thought of using explicit array, following, didn't work:

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

i'm unsure if valid use-case dictionary, or if there data structure should using. python has way of surprising me. know python magic make work?

how this:

def fancy_dict(*args):     'pass in list of tuples, key/value pairs'     ret = {}     k,v in args:         in k:             ret[i] = v     return ret 

then, can:

>>> dic = fancy_dict((range(10), 'hello'), (range(100,125), 'bye')) >>> dic[1] 'hello' >>> dic[9] 'hello' >>> dic[100] 'bye' >>>  

you can add logic inside of fancy_dict say, check if item string or if iterable , create dictionary accordingly.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -