简体   繁体   中英

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?

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

The defaultdict constructor can take two arguments, where the first is the function to use for the default, and the second a mapping (dict). It copies the keys/values from the dict passed in.

 >>> d = defaultdict(list, {'a': [1,2,3]})
 >>> d['a']
 [1, 2, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM