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

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

在字典中搜索特定列表,并將列表作為python中的值

在字典中搜索特定列表,并將列表作為python中的值

德瑪西亞99 2023-09-05 17:34:39
我有一本字典,其中字符串作為鍵,列表作為值。我現在有另一個列表(list2),我想搜索是否有包含 list2 所有項目的字典值列表。然后我希望輸出成為匹配字典值列表的鍵。我的代碼現在看起來像這樣:for elem in list2:    for elem2 in dict.keys():        if all(item in elem2 foritem in list2):            print(elem2)value_found_list = dict.get(elem2)print(value_found_list)編輯最小可重現示例:dict{"key1": ['item1', 'item2', 'item3'], "key2": ['item2', 'item4', 'item5'],"key3": ['item3', 'item6', 'item4']}list = ['item2', 'item3']我如何使用此數據返回哪個字典鍵包含列表中的所有項目?
查看完整描述

3 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

如果您打算進行會員資格檢查,最好將第二個更改list為 a 。set


這是一個簡短的函數,可以做到這一點。


編輯:由于您以相反的方式進行操作,因此僅使用dict. set然而,首先將它們采用 a 的形式可能更有意義。Aset經過哈希處理,這意味著更快的查找時間。如果您的lists 很長,那么采用這種形式可以節省一些計算時間。


def get_key(dct, lst2):

    # iterate through every key and list

    for key, lst in dct.items():

        # if all the list items are present in your second list

        if all(i in lst for i in lst2):

            return key

    # default to returning None

    return None


dct = {

"key1": ['item1', 'item2', 'item3'], 

"key2": ['item2', 'item4', 'item5'],

"key3": ['item3', 'item6', 'item4']

}

lst = ['item2', 'item3']

print(get_key(dct, lst))

你出錯的地方就在這里。


    for elem2 in dict.keys():

        if all(item in elem2 foritem in list2):

elem2是一個字符串鍵。item in elem2正在尋找鍵中的完整字符串。 dict.values()返回您可能正在查找的值或列表。


但是,dict.items()將鍵和值作為元組返回,這可能正是您所需要的。


查看完整回答
反對 回復 2023-09-05
?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

看這個


a = {'one':[1, 2, 3, 4], 'two':[5, 6, 7, 8], 'three':[9, 10]}

b = {'four':[1, 2, 3, 4], 'five':[6, 7, 8], 'six':[9, 10]}

for akey in a:

    for bkey in b:

        if a[akey] == b[bkey]:

            print(akey, bkey)

輸出:


one four

three six


查看完整回答
反對 回復 2023-09-05
?
LEATH

TA貢獻1936條經驗 獲得超7個贊

l=[i for i in your_dict if set(your_dict[i]).union(set(list2))==set(your_dict[i])]


print(l)

為了:


your_dict={

"key1": ['item1', 'item2', 'item3'], 

"key2": ['item2', 'item4', 'item5'],

"key3": ['item3', 'item6', 'item4']

}

list2 = ['item2', 'item3']

輸出是:


['key1']


查看完整回答
反對 回復 2023-09-05
  • 3 回答
  • 0 關注
  • 303 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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