问题
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