有没有办法使字典关键字成为范围? [英] Is there a way to have a dictionary key be a range?
问题描述
如果这很明显,请原谅我,但是我对Python非常新手.我已经找到了从字典中获取多个键的方法,但这不是我要尝试的方法.
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" }
...但是键实际上不是字符串,并且在给定范围内的任何数字都映射到该值.因此,例如,my_dict[9]
应该返回foo
,就像my_dict[3]
应该那样.我想到要使用一个像下面这样的显式数组,但是没有用:
... 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",
我不确定这是否是字典的有效用例,或者是否应该使用其他数据结构.但是Python总是让我感到惊讶.那么有人知道Python魔术可以使这项工作成功吗?
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?
推荐答案
这是怎么回事:
def fancy_dict(*args):
'Pass in a list of tuples, which will be key/value pairs'
ret = {}
for k,v in args:
for i in k:
ret[i] = v
return ret
然后,您可以:
>>> dic = fancy_dict((range(10), 'hello'), (range(100,125), 'bye'))
>>> dic[1]
'hello'
>>> dic[9]
'hello'
>>> dic[100]
'bye'
>>>
您还可以在fancy_dict
内添加逻辑,例如,检查项目是否为字符串或是否可迭代,并相应地创建字典.
You can also add logic inside of fancy_dict
to say, check if an item is a string or if it is iterable and create the dictionary accordingly.
这篇关于有没有办法使字典关键字成为范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!