Python 字典 : "in" vs "get"

标签 python python-3.x dictionary hash

在字典中搜索元素时,我对“in”和“get”的使用有点困惑。

根据这个时间复杂度表,here :当使用“in”时,我们得到 O(n) 与“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"

我不明白当它们都可以实现相同的事情时,使用 get 会如何改变时间复杂度。除了 get 调用实际上会返回该值(如果找到)。

问题:当它们都达到相同的结果时,“in”时间复杂度是 O(n) 而“get”的时间复杂度仅为 O(1) 是怎么回事?如果这是真的,是否有理由在字典中使用“in”?

最佳答案

get()如果键存在于字典中,则返回给定键的值。
in根据键是否存在于字典中,返回一个 bool 值。

使用 get()如果你需要值(value)。使用 in如果您只需要测试 key 是否存在。

关于Python 字典 : "in" vs "get",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46509361/

相关文章:

python - 防止python截断用作键的数据

python-3.x - 识别 git 提交的实际分支名称

c++ - std::map 如何在没有比较函数的情况下将一对作为键映射到它的值

python - 如果 Dataframe 中的数据属于同一流,如何对它们进行分组?

python - 为什么具有正确 header 的 requests.get 返回空内容?

python-3.x - "Command ' 在 MiniConda 中导入 ' not found, but can be installed with"

python - 使用shutil.make_archive压缩文件时出现意外文件

string - 理解 Scala 中的 String 和 map 方法

python - 如何从 cython 安装文件中删除 -pthread 编译器标志

python - 如何从 "i view X"打开使用 "SMI"系统创建的 *.idf 眼动仪数据