亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我可以從它的值中獲取 python 字典的索引嗎?

我可以從它的值中獲取 python 字典的索引嗎?

料青山看我應如是 2022-07-12 15:50:36
dict = {  a: [(21, ['one', 'two', 'three'])]  b: [(21, ['four', 'five'])]}我想開發一個函數,當我將“三”作為參數傳遞時返回一個。我怎樣才能做到這一點?
查看完整描述

2 回答

?
慕標5832272

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


查看完整回答
反對 回復 2022-07-12
?
浮云間

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


查看完整回答
反對 回復 2022-07-12
  • 2 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號