3 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
如果您打算進(jìn)行會(huì)員資格檢查,最好將第二個(gè)更改list為 a 。set
這是一個(gè)簡短的函數(shù),可以做到這一點(diǎn)。
編輯:由于您以相反的方式進(jìn)行操作,因此僅使用dict. set然而,首先將它們采用 a 的形式可能更有意義。Aset經(jīng)過哈希處理,這意味著更快的查找時(shí)間。如果您的lists 很長,那么采用這種形式可以節(jié)省一些計(jì)算時(shí)間。
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))
你出錯(cuò)的地方就在這里。
for elem2 in dict.keys():
if all(item in elem2 foritem in list2):
elem2是一個(gè)字符串鍵。item in elem2正在尋找鍵中的完整字符串。 dict.values()返回您可能正在查找的值或列表。
但是,dict.items()將鍵和值作為元組返回,這可能正是您所需要的。

TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
看這個(gè)
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

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
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']
添加回答
舉報(bào)