Create default values for dictionary in python
Use a collections.defaultdict. It's designed precisely for this purpose.
Of course; this is Python after all: Just use a defaultdict.
Well if you are trying to memoize something, its best to use a Memoize class and decorators.
class Memoize(object):
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if args not in self.cache:
self.cache[args] = self.func(*args)
return self.cache[args]
Now define some function to be memoized, say a key-strengthening function that does say 100,000 md5sums of a string hashes:
import md5
def one_md5(init_str):
return md5.md5(init_str).hexdigest()
@Memoize
def repeat_md5(cur_str, num=1000000, salt='aeb4f89a2'):
for i in xrange(num):
cur_str = one_md5(cur_str+salt)
return cur_str
The @Memoize
function decorator is equivalent to defining the function and then defining repeat_md5 = Memoize(repeat_md5)
. The first time you call it for a particular set of arguments, the function takes about a second to compute; and the next time you call its near instantaneous as it read from its cache.
As for the method of memoization; as long as you aren't doing something silly (like the first method where you do if key in some_dict.keys()
rather than if key in some_dict
) there shouldn't be much a significant difference. (The first method is bad as you generate an array from the dictionary first, and then check to see if the key is in it; rather than just check to see whether the key is in the dict (See Coding like a pythonista)). Also catching exceptions will be slower than if statements by nature (you have to create an exception then the exception-handler has to handle it; and then you catch it).