0

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'
asked Sep 12, 2017 at 8:28
1
  • 1
    just do final_data_row = defaultdict(list) Commented Sep 12, 2017 at 8:30

1 Answer 1

2

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

answered Sep 12, 2017 at 8:31
Sign up to request clarification or add additional context in comments.

1 Comment

Figured this one out right after posting! ;) Thanks for your help!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.