【问题标题】:Python: Does key exist in dictionary (Python 3.1)Python:字典中是否存在键(Python 3.1)
【发布时间】:2011-04-28 18:37:41
【问题描述】:
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 中已被弃用,除此之外我还没有找到其他解决方案。我做错了什么?

【问题讨论】:

  • 如果你在解析参数,为什么不直接使用optparse? (docs.python.org/library/optparse.html)
  • optparse 已被 argparse 取代,它将在 Python 的未来版本中维护(尽管目前我认为没有非常实质性的差异)。我相信它受到 2.7+ 和 3.2+ 的支持。

标签: python dictionary key-value


【解决方案1】:

只要"help" in arguments

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

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

另外请注意,您可以编写 arguments = {} 作为创建字典的更 Pythonic 方式。

【讨论】:

    【解决方案2】:

    您忘记了帮助周围的引号。因为 help 是内置的,python 不会像平常那样抱怨。

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 2010-11-30
      • 2021-02-28
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多