Python不在字典条件语句中的表现

scy*_*gon 1 python performance dictionary

有人知道关于速度和资源使用什么更好的方法吗?链接到一些可信赖的来源将不胜感激。

if key not in dictionary.keys():
Run Code Online (Sandbox Code Playgroud)

要么

if not dictionary.get(key):
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 6

首先,你会

if key not in dictionary:
Run Code Online (Sandbox Code Playgroud)

因为字典是通过键来迭代的。

其次,这两种说法是不等价的-如果相应的值是falsy第二条件将是真实的(0""[]等),不仅如果键不存在。

最后,第一种方法肯定是更快,更pythonic。函数/方法调用很昂贵。如果不确定,timeit