Search code examples
pythondefaultdict

How can I convert defaultdict(Set) to defaultdict(list)?


I have a defaultdict(Set):

from sets import Set
from collections import defaultdict
values = defaultdict(Set)

I want the Set functionality when building it up in order to remove duplicates. Next step I want to store this as json. Since json doesn't support this datastructure I would like to convert the datastructure into a defaultdict(list) but when I try:

defaultdict(list)(values)

I get: TypeError: 'collections.defaultdict' object is not callable, how should I do the conversion?


Solution

  • You can use following:

    >>> values = defaultdict(Set)
    >>> values['a'].add(1)
    >>> defaultdict(list, ((k, list(v)) for k, v in values.items()))
    defaultdict(<type 'list'>, {'a': [1]})
    

    defaultdict constructor takes default_factory as a first argument which can be followed by the same arguments as in normal dict. In this case the second argument is a generator expression that returns tuples consisting key and value.

    Note that if you only need to store it as a JSON normal dict will do just fine:

     >>> {k: list(v) for k, v in values.items()}
     {'a': [1]}