Python 获取数组中的字典键值
与此类似 但这一次,值位于数组中。我想到的解决方案是循环字典中的每个项,然后再次循环值对中的每个项。但从表面上看,这是密集的。这是唯一的办法吗Python 获取数组中的字典键值,python,dictionary,Python,Dictionary,与此类似 但这一次,值位于数组中。我想到的解决方案是循环字典中的每个项,然后再次循环值对中的每个项。但从表面上看,这是密集的。这是唯一的办法吗 # a dictionary that contains ranges. this dictionary might have 1million keys and the range can have many values too dictionary = { "x": range(0,10), "y":
# a dictionary that contains ranges. this dictionary might have 1million keys and the range can have many values too
dictionary = {
"x": range(0,10),
"y": range(11,20),
"z": range(21,30)
.
.
.
}
get_dictionary_value = 16
for k,v in dictionary.items():
for item in v:
if get_dictionary_value = item:
print("the key is {}".format(k)) #the output will be "the key is y"
这是以下方面的典型用例: 返回:
y
为了坚持您的方法,您可以使用前面提到的@Anton vBR中的in语句。这将检查数据结构中是否包含某些项(不仅适用于列表)
将返回与查询匹配的键为什么不在dictionary.items()中为k,v返回
:如果在v:print(…)中获取dictionary\u项
?如果只有一个键,您也可以在该点上断开。如果你经常这样做,你也可以考虑替代的数据结构(甚至只是一个颠倒的字典)。JorrSape谢谢,你认为在这方面更好的方法是什么?我没有问题,但是我只是想知道这是否是内存密集。这是内存密集型的吗?我知道迭代器比传统的循环更好。我不确定具体从哪个角度来看,但对于python3来说,这应该是一个生成器上的循环。这么快的回答是:不。
y
d = {
"x": range(0,10),
"y": range(11,20),
"z": range(21,30)
}
query = 16
for k,v in d.items():
if query in v: k
>>> 'y'