[英]Cast dict to defaultdict
The following code uses the {} operator to combine two defaultdicts.以下代码使用 {} 运算符组合两个 defaultdict。
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.但是,正如我们看到的,如果我们运行它,
{}
运算符返回一个dict
类型而不是一个defaultdict
类型。
Is there a way to cast a dict
back to a defaultdict?有没有办法将
dict
回 defaultdict?
You can use unpacking directly in a call to defaultdict
.您可以在调用
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
. defaultdict
是dict
的子类,并将这些参数传递给其父类以创建字典,就像它们已传递给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
:这种方法的好处是你不需要重新指定
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). defaultdict
构造函数可以接受两个参数,其中第一个是用于默认值的函数,第二个是映射 (dict)。 It copies the keys/values from the dict passed in.它从传入的字典中复制键/值。
>>> d = defaultdict(list, {'a': [1,2,3]})
>>> d['a']
[1, 2, 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.