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?
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'})
You can do it the long way. The benefit of this method is you don't need to re-specify the type of defaultdict
:
def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z
cc = merge_two_dicts(aa, bb)
Unpacking in a single expression works but is inefficient:
n = 500000
d1 = defaultdict(int)
d1.update({i: i for i in range(n)})
d2 = defaultdict(int)
d2.update({i+n:i+n for i in range(n)})
%timeit defaultdict(int, {**d1, **d2}) # 150 ms per loop
%timeit merge_two_dicts(d1, d2) # 90.9 ms per loop
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