Python:字典中是否存在键(Python 3.1)
arguments=dict()
if (arg.find("--help") == 0):
arguments["help"] = 1
if help in arguments:
#this doesnt work
print(arguments["help"]) # This will print 1
无法查明某个键是否已定义。 .has_key 在 2.7 中已被弃用,我还没有找到除此之外的其他解决方案。我做错了什么?
arguments=dict()
if (arg.find("--help") == 0):
arguments["help"] = 1
if help in arguments:
#this doesnt work
print(arguments["help"]) # This will print 1
Cannot find out if a certain key has been defined. .has_key has been deprecated in 2.7 and I haven't find other solution than this. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需在参数中执行
“help”
即可。在您的示例中,您在参数中编写了
help
,字符串周围没有引号。因此,它假设询问内置函数help
是否是字典中的键。另请注意,您可以编写
arguments = {}
作为创建字典的更 Pythonic 的方式。Just do
"help" in arguments
.In your example you have written
help in arguments
without quotes around the string. Hence it assumes to ask whether the built-in functionhelp
is a key in your dictionary.Also notice that you can write
arguments = {}
as a more pythonic way of creating a dict.您忘记了帮助周围的引号。因为 help 是内置的,所以 python 不会像平常那样抱怨。
You forgot the quotes around help. Because help is a builtin, python isn't complaining like it normally would.