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

馋奶兔 提交于 2021-02-07 18:49:01

问题


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?


回答1:


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]}



回答2:


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()}



回答3:


Say that a = set(), and you have populated it already with unique values. Then, when using defaultdict you could cast it into a list: defaultdict(list(a))



来源:https://stackoverflow.com/questions/37212808/how-can-i-convert-defaultdictset-to-defaultdictlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!