【问题标题】:Matching a 'Key' in a Dictionary from a String, and returning a 'Value'从字符串中匹配字典中的“键”,并返回“值”
【发布时间】:2020-12-03 21:35:41
【问题描述】:

尊敬的堆栈溢出社区:

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

例如:

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

print('注释:', end='') 用户输入 = 输入()

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

我想通过对输入应用“.split()”来解决这个问题,这样每个单词都会被隔离。

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

因此,在输入客户想提高他们的购买限额的示例中,它会匹配单词“limit”并返回通过网上银行进行的每日交易限额 .

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

【问题讨论】:

  • 你能告诉我们你已经尝试过什么吗?

标签: python string dictionary matching


【解决方案1】:

您可以使用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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多