使用字典尝试并排除异常 (Python)

Try and Except exceptions with a dictionary (Python)

假设我向用户询问一个词,如果这个词不是字典中的关键字,那么我想打印 "That word is not a key in the dictionary, try again"。我将如何使用 try 和 except 来做到这一点?这是我目前所拥有的。

dict = {"These": 1, "are": 2, "words": 3}
while True:
    try:
        w = input("Enter a word: ")
    except: 
        print("That word is not a key in the dictionary, try again")
    else:
        print("That word is a key in the dictionary")

访问地图中不存在的键时,您可能会遇到 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")

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

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")

有几件重要的事情要大声说出来。在没有 Exception 的情况下使用 except: 是非常糟糕的做法,因为它会捕获任何东西(比如 SystemExit or KeyboardInterrupt for instance, which will prevent your program from exiting correctly). dict is a name of a builtin function,所以你通过命名你的字典 dict.[= 来重新定义它19=]

正如其他人在评论中所建议的那样,您不需要 try/except 来执行此操作,除非您想了解有关 try/except 的更多信息。更好的方法是使用集合:

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")

您也可以通过使用 dict.get() 避免使用 try/except 块,其中 returns 映射到指定键的值,或者 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 作为变量名,因为它隐藏了保留关键字。