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

发布于 2022-02-17 09:44:06

我想在更新键的值之前测试一个键是否存在于字典中。我写了以下代码:

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

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

关注者
0
被浏览
89
1 个回答
  • 面试哥
    面试哥 2022-02-17
    为面试而生,有面试问题,就找面试哥。

    in是测试 a 中是否存在键的预期方法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关键字是最好的方法。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看