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)


access:  yellow
call mydefault
access:  blue
call mydefault
access:  yellow
access:  blue
access:  red
call mydefault
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

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 [ ]: