尝试并使用字典例外(Python)

时间:2018-06-25 21:27:02

标签: python dictionary try-except

假设我要求用户输入一个单词,如果该单词不是词典中的键,那么我要打印“该单词不是词典中的键,然后重试”。我将如何使用try和except做到这一点?这就是我到目前为止所拥有的。

<p>total items are:    {{total}}</p>

3 个答案:

答案 0 :(得分:4)

访问地图中不存在的键时,您可能会抓住KeyError

try:
    w = input("Enter a word: ")
    k[w]
except KeyError:
    print("That word is not a key in the dictionary, try again")
else:
    print("That word is a key in the dictionary")

答案 1 :(得分:2)

要直接回答您的问题,此代码可以满足您的需求:

words = {"these": 1, "are": 2, "words": 3}
while True:
    try:
        value = words[input("Enter a word: ").trim().lower()]
    except KeyError: 
        print("That word is not a key in the dictionary, try again")
    else:
        print("That word is a key in the dictionary")

将重要的事情结合起来。在没有except:的情况下使用Exception是非常不好的做法,因为它将捕获任何内容(例如SystemExitKeyboardInterrupt,这将阻止程序正确退出)。 dictbuiltin function的名称,因此您要通过命名字典dict重新定义它。

正如其他人在评论中所建议的那样,除非您想了解有关try / except的更多信息,否则您不需要try / except即可。更好的方法是使用set:

words = {"these", "are", "words"}
while True:
    if words[input("Enter a word: ").trim().lower()] in words:
        print("That word is a key in the dictionary")
    else:
        print("That word is not a key in the dictionary, try again")

答案 2 :(得分:1)

您还可以避免使用try / except块,方法是使用dict.get(),它返回映射到指定键的值;如果找不到键,则返回None(默认值)。您可以将此默认值更改为所需的任何值。

代码:

data = {"These": 1, "are": 2, "words": 3}

# make all keys lowercase
data = {k.lower(): v for k, v in data.items()}

while True:
    w = input("Enter a word: ")

    if data.get(w.lower()):
        print("That word is a key in the dictionary")
    else:
        print("That word is not a key in the dictionary, try again")

输出:

Enter a word: these
That word is a key in the dictionary
Enter a word: These
That word is a key in the dictionary
Enter a word: blah
That word is not a key in the dictionary, try again

注意:上面的键已转换为小写形式,以避免在查找键时不区分大小写。您也不应使用dict作为变量名,因为它会遮盖保留关键字。