您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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关键字是最好的方法

你不必呼叫按键:

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

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

其他 2022/1/1 18:21:51 有530人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶