Search code examples
pythonsetdefaultdictconceptuallanguage-concepts

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?


Solution

  • 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.