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

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

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

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

最佳答案

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 = {}

for i in range(10):
    d[i] = d.get(i, 0) + 1

要为 每个 键提供默认值,请使用 dict.setdefault()每个作业:

d = {}

for i in range(10):
    d[i] = d.setdefault(i, 0) + 1

或使用 defaultdict来自 collections模块:

from collections import defaultdict

d = defaultdict(int)

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

https://stackoverflow.com/questions/1602934/

相关文章:

windows - 如何在 Windows 上安装 pip?

python - "Least Astonishment"和可变默认参数

python - 如何通过引用传递变量?

python - 在一行中捕获多个异常( block 除外)

python - 如何制作函数装饰器并将它们链接在一起?

python - 如何向字典添加新键?

python - 使用 __init__() 方法理解 Python super()

python - __str__ 和 __repr__ 有什么区别?

python - 如何获取当前时间?

python - 我如何做一个时间延迟?