Python:字典中是否存在密钥(Python 3.1)

Bla*_*123 -1 python dictionary key-value

arguments=dict()
if (arg.find("--help") == 0):
  arguments["help"] = 1
if help in arguments:
  #this doesnt work

print(arguments["help"]) # This will print 1
Run Code Online (Sandbox Code Playgroud)

无法确定是否已定义某个键..has_key已在2.7中弃用,我还没有找到其他解决方案.我究竟做错了什么?

Tho*_*hle 8

做吧"help" in arguments.

>>> arguments = dict()
>>> arguments["help"]=1
>>> "help" in arguments
True
Run Code Online (Sandbox Code Playgroud)

在您的示例中,您help in arguments在字符串周围没有引号.因此,它假设询问内置函数help是否是字典中的键.

另请注意,您可以将其arguments = {}作为创建词典的更加pythonic方式.