我有 2 个示例列表,我想要实现的是获得nested带有值总和的默认字典。
下面的代码效果很好:
from collections import defaultdict
l1 = [1,2,3,4]
l2 = [5,6,7,8]
dd = defaultdict(int)
for i in l1:
for ii in l2:
dd[i] += ii
但我想做的是在中创建一个默认密钥d
字典:
from collections import defaultdict
l1 = [1,2,3,4]
l2 = [5,6,7,8]
dd = defaultdict(int)
for i in l1:
for ii in l2:
dd[i]['mykey'] += ii
这会引发错误:
Traceback (most recent call last):
File "/usr/lib/python3.6/code.py", line 91, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "<string>", line 12, in <module>
TypeError: 'int' object is not subscriptable
基本上我无法理解的是是否有机会混合defaultdict(dict)
and defaultdict(int)
.