![](/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.