将字典项初始化为 defaultdict(list)

Initialize dictionary items as defaultdict(list)

我正在尝试简化这段代码:

final_data_row = dict()
final_data_row['param1'] = []
final_data_row['param2'] = []
final_data_row['param3'] = []
final_data_row['param4'] = []

变成这样的东西:

from collections import defaultdict

final_data_row = dict()
for param in ['param1', 'param2', 'param3', 'param4']:
    final_data_row[param] = defaultdict(list)

但是当我想向其中一个字典项添加内容时,就像这样:

final_data_row['param1'].append('test value')

它给我一个错误:

AttributeError: 'collections.defaultdict' object has no attribute 'append'

两个片段并不相同:第一个片段创建 4 个条目作为列表,第二个片段创建 4 个条目作为 defaultdicts。所以键的每个值现在都是 defaultdict,不能在上面使用 append

取决于你想做什么:

只定义这 4 个键:不需要 defaultdict

final_data_row = dict()
for param in ['param1', 'param2', 'param3', 'param4']:
    final_data_row[param] = []

或听写理解:

final_data_row = {k:[] for k in ['param1', 'param2', 'param3', 'param4']}

如果你想要一个完整的 defaultdict: 一行:

final_data_row = defaultdict(list)

(可以添加任意多个键,不固定为param[1234]个键