小编典典

检查字典中是否已存在给定键

python

我想在更新密钥值之前测试字典中是否存在密钥。我写了以下代码:

if 'key1' in dict.keys():
  print "blah"
else:
  print "boo"

我认为这不是完成此任务的最佳方法。有没有更好的方法来测试字典中的键?


阅读 573

收藏
2020-02-11

共2个答案

小编典典

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()重复使用,也可以defaultdictcollections模块中使用它,如下所示:

from collections import defaultdict

d = defaultdict(int)

for i in range(100):
    d[i % 10] += 1

但总的来说,in关键字是最好的方法。

2020-02-11
小编典典

你不必呼叫按键:

if 'key1' in dict:
  print("blah")
else:
  print("boo")

这将更快,因为它使用字典的哈希而不是进行线性搜索(调用键可以做到)。

2020-02-11