首页 > 解决方案 > 从字符串中匹配字典中的“键”,并返回“值”

问题描述

亲爱的堆栈溢出社区:

我一直在尝试解决用户输入一个字符串的情况,然后将字符串中的单词与预定义字典中的“键”进行比较,以查看是否匹配。如果匹配退出,则为字典中的“键”返回相应的“值”。

例如:

thisdict = { "limit": "网上银行每日交易限额", "payout": "网上银行支付贷款", }

print('注:', end='') user_input = input()

假设用户在提示中输入以下内容: 客户想增加他们的购买限额

我正在考虑通过将“.split()”应用于输入来解决它,这样每个单词都会被隔离。

然后,运行“for 循环”以将字符串中的每个单词与字典中的每个键匹配。随后,返回与字符串中的单词匹配的“键”的任何“值”。

因此,在输入客户想增加购买限额的示例中,它会匹配“限额”一词并通过网上银行返回每日交易限额

我在将其转换为 Python 代码时遇到了困难,希望能得到一些帮助。

标签: pythonstringdictionarymatching

解决方案


您可以使用in来测试单词是否是字典中的键:

def lookup(dct, sentence):
    """
    splits the input sentence into words and returns the value from dct for
    the first word that is a key, or None if none are found.
    """
    for word in sentence.split():
        if word in dct:  # <== this tests the word against the dictionary keys
            return dct[word]  # <== do the lookup (we know the key exists)
    return None  # <== no matches were found in the 'for' loop


thisdict = { "limit": "daily transaction limits through online banking", "payout": "payout loan through online banking", }

print('Notes: ', end='')
user_input = input()

print(lookup(thisdict, user_input))

推荐阅读