Python:如何判断字典中是否存在键(Python 3.1)

-1 投票
2 回答
1313 浏览
提问于 2025-04-16 16:36
arguments=dict()
if (arg.find("--help") == 0):
  arguments["help"] = 1
if help in arguments:
  #this doesnt work

print(arguments["help"]) # This will print 1

我不知道怎么判断一个特定的键是否已经定义过。在2.7版本中,.has_key这个方法已经不再使用了,我找不到其他的解决办法。请问我哪里做错了?

2 个回答

3

你忘了在“help”这个词周围加上引号。因为“help”是Python自带的一个功能,所以Python并不会像平常那样报错。

7

只需要写 "help" in arguments

>>> arguments = dict()
>>> arguments["help"]=1
>>> "help" in arguments
True

在你的例子中,你写了 help in arguments,但是没有把字符串用引号括起来。所以它就会认为你在问内置函数 help 是否是你字典里的一个键。

另外,注意你可以用 arguments = {} 这种更符合Python风格的方式来创建字典。

撰写回答