What type of datastructure does 'collections.defaultdict(set)' create?

24 Views Asked by At

Here, we are using set as the missing value default, how can we use an undefined set for that purpose?

1

There are 1 best solutions below

3
Mikael Öhman On BEST ANSWER

defaultdict doesn't take a value, it takes a callable thing that it can call (with no arguments) to construct the value when it needs to. Typically a constructor of a class, or a function, like lambda: 'Hello'.

Each new value will in this case be a set(), which is an empty set.

>>> d = collections.defaultdict(set)
>>> print(d['new_key'])
set()

Your datastructure is a dictionary of keys to sets, with an empty set as the default value.