Is the defaultdict in Python's collections module really faster than using setdefault?
问题 I've seen other Python programmers use defaultdict from the collections module for the following use case: from collections import defaultdict s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] def main(): d = defaultdict(list) for k, v in s: d[k].append(v) I've typically approached this problem by using setdefault instead: def main(): d = {} for k, v in s: d.setdefault(k, []).append(v) The docs do in fact claim that using defaultdict is faster, but I've seen the