Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 287
jonalv Avatar asked Mar 13 '23 07:03

jonalv


2 Answers

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]}
like image 127
niemmi Avatar answered Apr 01 '23 18:04

niemmi


defaultdict(list, values)

The defaultdict constructor works like the dict constructor with a mandatory default_factory argument in front. However, this won't convert any existing values from Sets to lists. If you want to do that, you need to do it manually:

defaultdict(list, ((k, list(v)) for k, v in values.viewitems()))

You might not even want a defaultdict at all at that point, though:

{k: list(v) for k, v in values.viewitems()}
like image 44
user2357112 supports Monica Avatar answered Apr 01 '23 19:04

user2357112 supports Monica