【问题标题】:How do I check that a definition and a key exist in a Python dict [duplicate]如何检查 Python dict 中是否存在定义和键 [重复]
【发布时间】:2019-11-06 12:31:26
【问题描述】:

我想检查两个用户的输入是否一起作为键值对存在于字典中;例如:

dict = {"ABC" : 123, "DEF" : 456}
firstInput= input("Please enter your age: ")
secondInput= input("Please enter your name: ")

然后: 如果用户的输入分别是“ABC”和 123,或者“DEF”和 456,它将返回一个值,否则返回另一个值。

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    我不想给出代码示例,因为这个问题似乎可以通过简单的 Google 搜索来回答。话虽这么说,是这样的:

    try:
        value = dict[firstInput]
    except KeyError:
        value = 'No entry for {}'.format(firstInput)
    
    if value == secondInput:
        # success 
    else:
        return 'Entry found but incorrect value supplied'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 2016-08-28
      相关资源
      最近更新 更多