python - 需要一个 defaultdict,其值为两个列表

标签 python dictionary defaultdict

在Python中,我想要类似的东西

dict = defaultdict((list,list))

本质上,对于每个键我都想要两个列表!

通过上面的代码片段,我得到错误第一个参数必须是可调用的。我怎样才能实现这个目标?

最佳答案

将创建空列表的函数作为参数提供给 defaultdict:

from collections import defaultdict

def pair_of_lists():
    return [[], []]

d = defaultdict(pair_of_lists)

d[1][0].append(3)
d[1][1].append(42)

print(d)
# defaultdict(<function pair_of_lists at 0x7f584a40b0d0>, {1: [[3], [42]]})

关于python - 需要一个 defaultdict,其值为两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53251716/

相关文章:

python - 使用 boto3 从 aws lambda 调用 amazon lex 时出错

python - 为什么偶数和奇数不能打印出正确的答案?

python - 评估 python 中元组的字符串表示形式

python : Get list by index not key in defaultdict

python - 构建 JSON 格式时出现问题。在字典和集合之间选择?

python - 是否可以通过Python获取页面排名等信息?

python - 不对整个终端使用 Npyscreen

python - 使用一些重复元素从 CSV 文件中构建和提取多维 Python 字典中的值

ios - 使用循环打印字典的值

Python - 通过键中的汉明距离对 defaultdict 值进行分组