Search code examples
pythonpython-3.xdictionarydefaultdictpython-collections

Cast dict to defaultdict


The following code uses the {} operator to combine two defaultdicts.

from collections import defaultdict
aa=defaultdict(str)
bb=defaultdict(str)
aa['foo']+= '1'
bb['bar']+= '2'
cc = {**aa,**bb}
type(cc)

But, as we see if we run this, the {} operator returns a dict type not a defaultdict type.

Is there a way to cast a dict back to a defaultdict?


Solution

  • You can use unpacking directly in a call to defaultdict. defaultdict is a subclass of dict, and will pass those arguments to its parent to create a dictionary as though they had been passed to dict.

    cc = defaultdict(str, **aa, **bb)
    # defaultdict(<class 'str'>, {'bar': '2', 'foo': '1'})