F. Elliot
F. Elliot

Reputation: 71

Initialize dictionary items as defaultdict(list)

I'm trying to simplify this code:

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

into something like this:

from collections import defaultdict

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

but when I wanted to add something to one of the dictionary items, like so:

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

it gives me an error:

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

Upvotes: 0

Views: 95

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

Both snippets aren't equivalent: the first one creates 4 entries as lists, the second one creates 4 entries as defaultdicts. So each value of the key is now a defaultdict, can't use append on that.

Depending on what you want to do:

Define only those 4 keys: No need for defaultdict

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

or with dict comprehension:

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

If you want a full defaultdict: one line:

final_data_row = defaultdict(list)

(you can add as many keys you want, not fixed to param[1234] keys

Upvotes: 2

Related Questions