我想在更新键的值之前测试一个键是否存在于字典中。 我写了以下代码:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的键?
最佳答案
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
关于python - 检查给定键是否已存在于字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1602934/