混合defaultdict(dict和int)以获得带有值总和的嵌套默认字典

问题描述 投票:0回答:2

我有 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)
defaultdict(int)

python python-3.x defaultdict
2个回答
6
投票

defaultdict 数据结构接收一个提供默认值的函数,因此如果您想创建一个

defautdict(int)
作为默认值,请提供一个执行此操作的函数,例如
lambda : defaultdict(int)
:

from collections import defaultdict
from pprint import pprint

l1 = [1, 2, 3, 4]

l2 = [5, 6, 7, 8]

dd = defaultdict(lambda : defaultdict(int))

for i in l1:

    for ii in l2:
        dd[i]['mykey'] += ii


pprint(dd)

输出

defaultdict(<function <lambda> at 0x7efc74d78f28>,
            {1: defaultdict(<class 'int'>, {'mykey': 26}),
             2: defaultdict(<class 'int'>, {'mykey': 26}),
             3: defaultdict(<class 'int'>, {'mykey': 26}),
             4: defaultdict(<class 'int'>, {'mykey': 26})})

5
投票

你想要一个默认整数字典的默认字典:

dd = defaultdict(lambda: defaultdict(int))

运行代码后:

>>> dd
{1: defaultdict(<class 'int'>, {'mykey': 26}),
 2: defaultdict(<class 'int'>, {'mykey': 26}),
 3: defaultdict(<class 'int'>, {'mykey': 26}),
 4: defaultdict(<class 'int'>, {'mykey': 26})}
© www.soinside.com 2019 - 2024. All rights reserved.