return a new dictionary-like object. let the caller specify the default value when container is intialized.
In [7]:
from collections import defaultdict
# define a default function
def mydefault():
print("call mydefault")
return list()
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(mydefault)
for k, v in s:
print("access: ", k)
d[k].append(v)
sorted(d.items())
Out[7]:
mydefault is called 3 times, because when each key is encountered for 1st time, it's not already in the mapping. the entry is automatically created using mydefault function.
In [ ]: