How does:
dict = {}
if key not in dict:
dict[key] = foo
Compare to:
try:
dict[key]
except KeyError:
dict[key] = foo
ie, is the look up of a key in anyway faster than the linear search through dict.keys(), that I assume the first form will do?
The answer depends on how often the key is already in the dict (BTW, has anyone mentioned to you how bad an idea it is to hide a builtin such as
dictbehind a variable?)If the key is in the dictionary this does one dictionary lookup. If the key is in the dictionary it looks up the dictionary twice.
This may be slightly faster for the case where the key is in the dictionary, but throwing an exception has quite a big overhead, so it is almost always not the best option.
This one is slightly tricky: it always involves two dictionary lookups: the first one is to find the
setdefaultmethod in thedictclass, the second is to look forkeyin thedctobject. Also iffoois an expression it will be evaluated every time whereas the earlier options only evaluate it when they have to.Also look at
collections.defaultdict. That is the most appropriate solution for a large class of situations like this.