2 回答

TA貢獻1966條經驗 獲得超4個贊
假設您已保存 中的所有值,請dict說:
dict = {
a: [(21, ['one', 'two', 'three'])]
b: [(21, ['four', 'five'])]}
然后,要訪問給定值的鍵,您需要反轉它們的關系(這將加快查找速度以換取更多內存):
lookup = {}
for key in dict.keys():
for value in dict[key][0][1]: #this is the list inside the tuple inside the list
lookup[value] = key
所以,當你在尋找所需值的鍵時,你可以去:
print('out:', lookup['three'])
這將輸出:
out: a

TA貢獻1829條經驗 獲得超4個贊
您可以通過迭代字典中的每個項目來做到這一點,但是在大型數據集中它可能效率低下。
def get_key(data, query):
for key, value in data.items():
if query in value[0][1]:
return key
return 'Not Found'
get_key(dictonary, word)然后,即使您的查找未能找到匹配項,您也可以調用您的函數并返回結果。
# Note i changed the name of the dictionary to dicton, as dict shouldn't be used as a variable name
print(get_key(dicton, 'three'))
print(get_key(dicton, 'seven'))
print(get_key(dicton, 'four'))
#a
#Not Found
#b
添加回答
舉報