The trouble with defaultdict
is that if you have a dictionary of dictionaries, all the subdictionaries also need to be of this type — annoying if you are getting them from elsewhere, for example, from parsing JSON.
It’s also subject to “shooting yourself in the foot” issues because it’s very easy to forget that you have a defaultdict
and do something like a['hello']
and forget that it will automatically create a value there.
I haven’t used defaultdict
in years. Instead, I use dict.setdefault
which gives any dictionary the same functionality and has the additional advantage that the creation or access part is visible when it happens, not elsewhere when the collection is created.
Note that this won’t work if creating the default item is expensive, but 9 times in 10 I’m writing d.getdefault(key, {})
so it just isn’t an issue.