I want to test whether the key exists in the dictionary before updating the value of the key. I wrote the following code:
if 'key1' in dict.keys(): print "blah" else: print "boo"
I don't think this is the best way to accomplish this task. Is there a better way to test keys in a dictionary?
Use
key in my_dict
directly instead ofkey in my_dict.keys()
:This will be faster because it uses an O(1) hash of the dictionary instead of performing an O(n) linear search of the list of keys.
in
Test whether the key exists indict
:Using
dict.get()
Provides a default value when the key does not exist:To provide a default value for each key, use
dict.setdefault()
on each job:...or better yet, use
defaultdict
from thecollections
module: