字典值是列表:
dictionary_1 = {"ABC": [1,2,3], "DEF":[4,5,6]}
如何从python中的5
获取"DEF"
的密钥,dictionary_1
?
答案 0 :(得分:2)
您可以创建反向字典:
>>> d = {i:k for k,v in dictionary_1.items() for i in v}
>>> d
{1: 'ABC', 2: 'ABC', 3: 'ABC', 4: 'DEF', 5: 'DEF', 6: 'DEF'}
>>> d[5]
'DEF'
答案 1 :(得分:1)
也许是这样的?
my_value = 5
for k, v in dictionary_1.iteritems():
if my_value in v:
print k
break
else:
print "No key, defaulting to GHJ"
演示:
In [12]: my_value = 8
In [13]: for k, v in dictionary_1.iteritems():
if my_value in v:
print "Key for %s is %s" % (my_value, k)
break
else:
print "No key found for %s, defaulting to GHJ" % my_value
No key found for 8, defaulting to GHJ
答案 2 :(得分:1)
你必须在字典中搜索:
try:
key = next(k for k, v in dictionary_1.iteritems() if 5 in v)
except StopIteration:
raise KeyError('Key for 5 not found')
这假设您正在寻找 a 键。要查找所有键,您可以使用列表推导:
keys = [k for k, v in dictionary_1.iteritems() if 5 in v]
列表可能为空。
答案 3 :(得分:0)
一种方法是:
dictionary_1 = {"ABC": [1,2,3], "DEF":[4,5,6]}
for k, v in dictionary_1.items():
if 5 in v:
print(k)
答案 4 :(得分:0)
假设你可以检查5是否在[4,5,6]列表中,你也可以尝试:
dictionary_1 = {"ABC": [1,2,3], "DEF":[4,5,6]}
print dictionary_1.keys()[dictionary_1.values().index([4,5,6])]