简体   繁体   中英

how to check whether specific word are included in dictionary value - Python

I want to make a search program but i stuck in specific alogrithm. First, I will get any word from users Then check wheter user's words are included in any keywords from di value. If user's words are included, then return key value as list type. If user's words are not included, then execute the program.

For example, if I input "nice guy", then function should return 'matthew' as list type.

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))
     

I keep stuck in for approaching the algorithm... I hope you guys give me any advice or idea to make this algorithm.

You can try like as below using list comprehension to pull out the matching keys:

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']

Another Output:

Enter word for search: guy
['matthew', 'dennis', 'alex']

comprehension

First, you can merge your dictionaries using ChainMap

from collections import ChainMap
chain = ChainMap(*dicts)

Then you can search using list comprehension for better performance

results = [v for v in chain.values() if 'keyword' in v]

filter

You can also do it with the python filter function

newDict = dict(filter(lambda elem: 'keyword' in elem[1], chain.items()))

Simple way is

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

Using list Comprehension.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM