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? 回答1: 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 If you wanted a default, you can always use dict.get() : d = dict() for i in xrange(100): key