![](/img/trans.png)
[英]How to Check whether a element exists in a python dictionary value which is a list?
[英]how to check whether specific word are included in dictionary value - Python
我想制作一個搜索程序,但我陷入了特定的算法。 首先,我會從用戶那里得到任何詞,然后檢查用戶的詞是否包含在來自 di 值的任何關鍵字中。 如果包含用戶的話,則返回鍵值作為列表類型。 如果不包括用戶的話,則執行該程序。
例如,如果我輸入“nice guy”,那么 function 應該返回“matthew”作為列表類型。
dic_1 = {'matthew':'he is a nice guy', 'dennis':'he is a bad guy', 'alex':'he is a good guy'}
dic_2 = {'manchester': 'city from england', 'tokyo':'city from japan', 'rome':'city from italy'}
def searchWords(*dicts):
list_check = []
search = input("Enter word for search: ")
for dic in dicts:
if search in dic[word]:
list_check.append(keyword)
else:
print("None")
break
print(searchWords(dic_1))
我一直堅持接近算法......我希望你們給我任何建議或想法來制作這個算法。
您可以嘗試如下使用列表理解來提取匹配的鍵:
dic_1 = {'matthew':'he is a nice guy', 'dennis':'he is a bad guy', 'alex':'he is a good guy'}
dic_2 = {'manchester': 'city from england', 'tokyo':'city from japan', 'rome':'city from italy'}
def searchWords(dictex):
search = input("Enter word for search: ")
return [k for k,v in dictex.items() if search in v]
print(searchWords(dic_1))
Output:
Enter word for search: nice guy
['matthew']
另一個 Output:
Enter word for search: guy
['matthew', 'dennis', 'alex']
首先,你可以使用ChainMap合並你的字典
from collections import ChainMap
chain = ChainMap(*dicts)
然后您可以使用列表理解進行搜索以獲得更好的性能
results = [v for v in chain.values() if 'keyword' in v]
您也可以使用 python過濾器function
newDict = dict(filter(lambda elem: 'keyword' in elem[1], chain.items()))
簡單的方法是
dic_1 = {'matthew':'he is a nice guy', 'dennis':'he is a bad guy', 'alex':'he is a good guy'}
dic_2 = {'manchester': 'city from england', 'tokyo':'city from japan', 'rome':'city from italy'}
def searchWords(*dicts):
lst = []
t = input('Write something to search:')
for dict_ in dicts:
for k,v in dict_.items():
if t in v:
lst+=[k]
return lst
使用列表理解。
def searchWords(*dicts):
t = input('Write something to search:')
lst = [k for dict_ in dicts for k,v in dict_.items() if t in v]
return lst
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.