python - Initialize dictionary items as defaultdict(list) -
i'm trying simplify code:
final_data_row = dict() final_data_row['param1'] = [] final_data_row['param2'] = [] final_data_row['param3'] = [] final_data_row['param4'] = []
into this:
from collections import defaultdict final_data_row = dict() param in ['param1', 'param2', 'param3', 'param4']: final_data_row[param] = defaultdict(list)
but when wanted add 1 of dictionary items, so:
final_data_row['param1'].append('test value')
it gives me error:
attributeerror: 'collections.defaultdict' object has no attribute 'append'
both snippets aren't equivalent: first 1 creates 4 entries lists, second 1 creates 4 entries defaultdict
s. each value of key defaultdict
, can't use append
on that.
depending on want do:
define 4 keys: no need defaultdict
final_data_row = dict() param in ['param1', 'param2', 'param3', 'param4']: final_data_row[param] = []
or dict comprehension:
final_data_row = {k:[] k in ['param1', 'param2', 'param3', 'param4']}
if want full defaultdict
: 1 line:
final_data_row = defaultdict(list)
(you can add many keys want, not fixed param[1234]
keys
Comments
Post a Comment