假设我有一本字典
d={'name1': ['A1', 'A2', 'A3', 'A4'], 'name2': ['E1', 'F1', 'G1'], 'name3'=['E3','F3']}
如何获取特定值的键。 例如,input='A1' 然后 output='name1'。 我正在考虑创建一个如下所示的函数,但由于字典中的列表,它可能无法正常工作(返回 None)
def reverse_search(dictionary, value):
keys = dictionary.keys()
for key in keys:
if dictionary.get(key) == value:
return key
我非常感谢您的帮助!
答案 0 :(得分:4)
您快要明白了,但字典的值为 list
,因此您不能使用 ==
,因为 ['A1', 'A2', 'A3', 'A4'] != 'A1'
您需要测试是否包含 {{1} }
in
对对和值都进行迭代更好
def reverse_search_from_dictionary(dictionary, value):
keys = dictionary.keys()
for key in keys:
if value in dictionary[key]: # no need of 'get', you're sure the key is present
return key
答案 1 :(得分:1)
如果该值存在,您可以签入列表:
def reverse_search_from_dictionary(dictionary, value):
keys = dictionary.keys()
for key in keys:
if value in dictionary.get(key):
return key
return "Not present"
答案 2 :(得分:1)
如果你打算多次这样做,首先构造一个反向字典会更高效:
>>> reverse_lookup = {k: v for v, l in d.items() for k in l}
然后
>>> reverse_lookup['A1']
'name1'
>>> reverse_lookup['G1']
'name2'
答案 3 :(得分:1)
试试下面的代码:
d = {'name1': ['A1', 'A2', 'A3', 'A4'],'name2': ['E1', 'F1', 'G1'], 'name3' : ['E3', 'F3']}
s = 'A1'
o = list(filter(lambda x:s in x[1],d.items()))[0][0]
print(o)
答案 4 :(得分:1)
我认为最简单的方法是这样
d = {'name1': ['A1', 'A2', 'A3', 'A4'],
'name2': ['E1', 'F1', 'G1'],
'name3': ['E3', 'F3']
}
def filter_dict(search_key):
k, v = tuple(filter(lambda x: search_key in x[1], d.items()))[0]
return k
search_key = 'A1'
print(filter_dict(search_key))