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?
dict.keys()creates a list of keys, according to the documentation docs.python.org/2/library/stdtypes.html#dict.keys but I'd be surprised if this pattern wasn't optimised for, in a serious implementation, to translate toif 'key1' in dict:. – Evgeni Sergeev Aug 12 '13 at 8:51x in dict.keys()to check for keys. And that happened because the usual way to iterate over keys in Java isfor (Type k : dict.keySet()), this habit causingfor k in dict.keys()to feel more natural thanfor k in dict(which should still be fine in terms of performance?), but then checking keys becomesif k in dict.keys()too, which is a problem... – Evgeni Sergeev Aug 12 '13 at 8:58if k in dict_:tests for presence of k in the KEYS of dict_, so you still don't needdict_.keys(). (This has bit me, as it reads to me like its testing for a value in dict. But it isn't.) – ToolmakerSteve Dec 16 '13 at 23:34