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_dictdirectly instead ofkey in my_dict.keys():if 'key1' in my_dict: print("blah") else: print("boo")This willbe fasterbecause it uses an O(1) hash of the dictionary instead of performing an O(n) linear search of the list of keys.
inTest whether the key exists indict:d = {"key1": 10, "key2": 23} if "key1" in d: print("this will execute") if "nonexistent key" in d: print("this will not")Using
dict.get()Provides a default value when the key does not exist:d = {} for i in range(100): key = i % 10 d[key] = d.get(key, 0) + 1To provide a default value foreachkey, use
dict.setdefault()on each job:d = {} for i in range(100): d[i % 10] = d.setdefault(i % 10, 0) + 1...or better yet, use
defaultdictfrom thecollectionsmodule: