Python 使用循环检查变量是否在字典中

Python 使用循环检查变量是否在字典中,python,dictionary,Python,Dictionary,所以在课堂上我做了一个蹩脚的文本冒险游戏。我想对照我的可接受单词词典检查用户输入的内容。然而,当我执行以下操作时,我得到一个“TypeError:”set“objectisnotsubscriptable”。我该如何着手解决这个问题 “游戏”的一小部分代码: def butts(): southLib={"long thing", "rough thing", "cylinder thing", "floor thing", "home"} userPoop = str(inp

所以在课堂上我做了一个蹩脚的文本冒险游戏。我想对照我的可接受单词词典检查用户输入的内容。然而,当我执行以下操作时,我得到一个“TypeError:”set“objectisnotsubscriptable”。我该如何着手解决这个问题

“游戏”的一小部分代码:

def butts():
    southLib={"long thing", "rough thing", "cylinder thing", "floor thing", "home"}

    userPoop = str(input("Would you like to poop in the long thing, rough thing, cylinder thing, floor thing, or home? None?"))

    while southLib[userPoop] == None:
        print("I do not understand")
        userPoop = str(input("Would you like to poop in the long thing, rough thing, cylinder thing, floor thing, or home? None?"))

butts()

进行适当的安全壳检查

while userPoop not in southLib:

如果要检查某个内容是否不在集合中,只需使用
not in
操作符:

>>> my_set = {"foo", "bar", "baz"}
>>> "foo" not in my_set
False
>>> "qux" not in my_set
True

(类似地,您可以在中使用
来检查集合中是否有内容。)

太棒了。我知道这很简单,但就是想不出一个表达问题的方法。谢谢。你正在创建一个集合,并且你正在尝试将它用作一个dict。它们是不同的类型。dict用于将键映射到值;仅收集一组值的集合。