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?
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]}
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()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With