defaultdict
in the collections
module. A feature of defaultdict
is that it automatically initializes the first value so you can simply focus on adding items.
In [1]:
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
print(d)
In [4]:
d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['a'].add(2)
d['b'].add(4)
print(d)
defauldict
is much simpler