检查字典中是否已经存在给定的键 [英] Check if a given key already exists in a dictionary
问题描述
在更新密钥值之前,我想测试字典中是否存在密钥。
我写了以下代码:
I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
我认为这是不是完成此任务的最佳方法。有没有更好的方法来测试字典中的键?
I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
推荐答案
in
是测试 dict
中的键的存在的预期方式。
in
is the intended way to test for the existence of a key in a dict
.
d = dict()
for i in xrange(100):
key = i % 10
if key in d:
d[key] += 1
else:
d[key] = 1
如果你想要一个默认值,你可以随时使用 dict.get()
:
If you wanted a default, you can always use dict.get()
:
d = dict()
for i in xrange(100):
key = i % 10
d[key] = d.get(key, 0) + 1
...如果您想始终确保任何键的默认值,您可以使用 defaultdict
从集合
模块,如下所示:
... and if you wanted to always ensure a default value for any key you can use defaultdict
from the collections
module, like so:
from collections import defaultdict
d = defaultdict(lambda: 0)
for i in xrange(100):
d[i % 10] += 1
但一般来说,关键字中的是最好的方式。
... but in general, the in
keyword is the best way to do it.
这篇关于检查字典中是否已经存在给定的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!