Skip to main content
 首页 » 编程设计

python之检查python dict中的值

2025年05月04日20soundcode

我正在尝试从用户输入中获取关键字,如果词典中有单词(dict),则返回一个元组(token, word),否则返回('error', word)

我将词典数据存储在字典中,每个键都有多个值,并循环查看输入的单词是否在其中一个中。

lexicons = { 
    'direction': ['north', 'south', 'east', 'west'], 
    'noun': ['car', 'bike'], 
} 
 
def scan(sentence): 
 
    result = [] 
    words = sentence.split() 
 
    for key, value in lexicons.items():   
        for word in words: 
            found = 0 
            if word in value: 
                found += 1 
            else: 
                pass 
 
            if found == 1: 
                result.append((key, word)) 
            else: 
                result.append(('error', word)) 
 
    return result 
 
scan('car bike QWER') 

我希望的是:

[('名词', '汽车'),('名词', '自行车'),('错误', 'QWER')]

但是我得到了:

[('错误', '汽车'),('错误', '自行车'),('错误', 'QWER'),('名词', '汽车'),('名词', '自行车'),('错误', 'QWER')]

我知道那是因为它会检查字典中的每个键,但我不知道如何修改它。

谢谢!

请您参考如下方法:

像这样:

lexicons = { 
    'direction': ['north', 'south', 'east', 'west'], 
    'noun': ['car', 'bike'], 
} 
 
def scan(sentence): 
 
    result = [] 
    words = sentence.split() 
 
    for word in words: 
        found = False 
        for key, value in lexicons.items():               
            if word in value: 
                found = True 
                result.append((key, word)) 
                break 
        if not found: 
            result.append(('error', word)) 
    return result 
 
scan('car bike QWER')