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
tests for the existence of a key in adict
:Use
dict.get()
to provide a default value when the key does not exist:To provide a default value for every key, either use
dict.setdefault()
on each assignment:...or better, use
defaultdict
from thecollections
module: