我想在更新键的值之前测试字典中是否存在键.
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
我认为这不是完成这项任务的最佳方式.有没有更好的方法来测试字典中的键?
我想在更新键的值之前测试字典中是否存在键.
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 = dict()
for i in range(100):
key = i % 10
d[key] = d.get(key, 0) + 1
如果您希望始终确保任何键的默认值,您可以重复使用dict.setdefault()
或collections
模块中的defaultdict
,如下所示:
from collections import defaultdict
d = defaultdict(int)
for i in range(100):
d[i % 10] += 1
但总的来说,in
关键字是最好的方法.