Skip to content

Latest commit

 

History

History
46 lines (29 loc) · 1.17 KB

111.md

File metadata and controls

46 lines (29 loc) · 1.17 KB

#查看某个给定的键是否已经在字典中

原问题地址:http://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary

##问题:

更新某键的值以前,我想先知道它是否存在于字典中。我写了以下代码:

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

我认为这不是完成此任务的最佳方法。有没有更好的方法来知晓字典中的某个键?

##回答:

in就是用于探知字典中是否存在某个键的一种方式

d = dict()

for i in xrange(100):
    key = i % 10
    if key in d:
        d[key] += 1
    else:
        d[key] = 1

如果你想要一个默认值,可以使用dict.get()

d = dict()

for i in xrange(100):
    key = i % 10
    d[key] = d.get(key, 0) + 1

如果你想一直确保某个键的默认值,可以使用collections模块中的defaultdict,就像下面这样:

from collections import defaultdict

d = defaultdict(lambda: 0)

for i in xrange(100):
    d[i % 10] += 1

但一般说来,关键字in是用于探知字典中是否存在某个键的最佳方法。