in是测试密钥是否存在的预期方法dict。
d = {"key1": 10, "key2": 23}
if "key1" in d:
print("this will execute")
if "nonexistent key" in d:
print("this will not")
如果您想使用默认值,可以随时使用dict.get():
d = dict()
for i in range(100):
key = i % 10
d[key] = d.get(key, 0) + 1
如果您想始终确保任何键的默认值,则可以dict.setdefault()重复使用,也可以defaultdict从collections模块中使用它,如下所示:
from collections import defaultdict
d = defaultdict(int)
for i in range(100):
d[i % 10] += 1
但总的来说,in关键字是最好的方法。