I write a lot of code where I use a dictionary of sets (or lists or counters, etc)
dict_set = {} if key not in dict_set: dict_set[key] = set() dict_set[key].add(item)
dict_set = {} dict_set.setdefault(key, set()).add(item)
from collections import defaultdict dict_set = defaultdict(set) dict_set[key].add(item)
setdefault
was added in Python 2.0 and I've been using (and loving) it for years.
It was only a month or two ago that I discovered collections.defaultdict
. Now I use it almost every day.
UPDATE: I forgot to mention that defaultdict
was added in Python 2.5. And owing to the fact that int()
returns 0
you can use defaultdict(int)
for a dictionary of counters.