Python词典:"in"vs"get"

Phi*_*lip 4 python hash dictionary python-3.x

在搜索字典中的元素时,我在使用"in"与"get"之间有点困惑.

根据这个时间复杂度表,这里:当使用"in"时我们得到O(n)vs"get"得到O(1).

在下面的这两个代码片段中,它们实现了相同的功能,但显然使用get会更快?

#Recall that for "get" the second parameter is returned if key is not found

#O(1) time complexity
if dict.get(key, False):
   return "found item"

#O(n) time complexity
if key in dict:
   return "found item"
Run Code Online (Sandbox Code Playgroud)

我不明白使用get会如何改变时间复杂度,因为它们可以实现相同的目标.除了get调用实际上会返回值,如果找到它.

问题:它是如何"中的"时间复杂度为O(n),而"得"只有O(1),当他们都获得同样的结果?如果这是真的,是否有理由在词典中使用"in"?

Cod*_*ice 9

get() 如果密钥存在于dict中,则返回给定密钥的值.

in 返回一个布尔值,具体取决于密钥是否存在于dict中.

get()如果您需要该值,请使用.使用in,如果你只需要测试,如果键存在.

  • @Phillip仔细阅读您提供的链接表.`in`的时间复杂度是针对列表而不是字典给出的. (5认同)
  • 对于 dict 来说,“in”和“get”的时间复杂度是相同的。[Wiki](https://wiki.python.org/moin/TimeComplexity#:~:text=is%20a%20list.-,dict,-%20Average%20Case) (4认同)