Devansh Gupta
Devansh Gupta

Reputation: 51

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

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

Upvotes: 0

Views: 26

Answers (1)

Mikael Öhman
Mikael Öhman

Reputation: 2375

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.

Upvotes: 1

Related Questions