Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 217
Ray Salemi Avatar asked Aug 09 '18 14:08

Ray Salemi


2 Answers

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'})
like image 117
Patrick Haugh Avatar answered Sep 18 '22 23:09

Patrick Haugh


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
like image 34
jpp Avatar answered Sep 17 '22 23:09

jpp