7 ms·
Unnecessary and awkward unless you really need a functional default. Use dict.setdefault for static defaults.
by jl2718 6y ago
Unnecessary and awkward unless you really need a functional default. Use dict.setdefault for static defaults.
- klyrs 5y agoYou've got that backwards. If you have a static default, that's what defaultdict is best at. If you need the default to depend on the key and you're the sole consumer of the dict, then you can use getdefault and setdefault -- but you incur the expense of computing that default whether or not you use it. If you need the default to depend on the key, and you can't control the scope that your dict will be used in, or you want to avoid computing the default when it's not needed, do that with a custom __missing__ method.