混合使用defaultdict(字典和整数)

4
我有两个示例列表,我想要达到的目标是获得一个嵌套的默认字典,其中包含值的总和。下面的代码效果很好:
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)

2个回答

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})}

谢谢你。我应该接受Daniel Mesejo的答案,因为他比你早几秒钟回复了我。不管怎样,还是谢谢! - matteo
不,他没有回答。我领先20秒(将鼠标悬停在“x小时前回答”上以查看确切日期),但无论谁需要声望 :) - Jean-François Fabre

5

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})})

太棒了!正是我所需要的。谢谢! - matteo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接