Python's defaultdict
The collection lib has many cool classes, like defaultdict. Basically it is a dict that you can initialize with some value, so you don’t need to check if the key exists before each assignment, such as the following annoying computation of histogram: d={}
if item not in d:
d[item]=0 d[item]+=1
can be easily replaced with: from collections import defaultdict d=defaultdict(int) d[item]+=1
The cool thing is that you can give arbitrary “default factories”, that are simply a function without parameters. So let’s say you want to have a dict, with each key holding a list of three elements, all initialized to zero: d[k]=[0,0,0] d=defaultdict(lambda: [0,0,0]) d["hello"][1]+=1
Or you can even have a nested defaultdict, if you want double indirection: d = defaultdict(lambda:defaultdict(int)) d["hello"]["world"]+=1
And you can go crazy with as many nested dicts as you wish!










