The addition of collections.defaultdict in Python 2.5 greatly reduced the need for dict‘s setdefault method. This question is for our collective education:
- What is
setdefaultstill useful for, today in Python 2.6/2.7? - What popular use cases of
setdefaultwere superseded withcollections.defaultdict?
You could say
defaultdictis useful for settings defaults before filling the dict andsetdefaultis useful for setting defaults while or after filling the dict.Probably the most common use case: Grouping items (in unsorted data, else use
itertools.groupby)Sometimes you want to make sure that specific keys exist after creating a dict.
defaultdictdoesn’t work in this case, because it only creates keys on explicit access. Think you use something HTTP-ish with many headers — some are optional, but you want defaults for them: