Default Dictionary
"The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict lets the caller specify the default(value to be returned) up front when the container is initialized."
Import
from collections import defaultdict
List
> list_dict = defaultdict(list)
> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
> for k, v in s:
list_dict[k].append(v)
> sorted(list_dict.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
Int
Setting the default_factory to int makes the defaultdict useful for counting (like a bag or multiset in other languages) When a letter is first encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero. The increment operation then builds up the count for each letter.
> int_dict = defaultdict(int)
> s = 'mississippi'
> int_dict = defaultdict(int)
> for k in s:
int_dict[k] += 1
> sorted(d.items())
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]```
Function
> def foo():
> return 'default value'
> func_dict = defaultdict(foo)
Set
Setting the default_factory to set makes the defaultdict useful for building a dictionary of sets:
> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
> d = defaultdict(set)
> for k, v in s:
d[k].add(v)
> sorted(d.items())
[('blue', {2, 4}), ('red', {1, 3})]