maazza maazza - 10 months ago 85
Python Question

Correct way to declare a defaultdict

I am currently trying to use a

in a unittest.
I declare it this way.

dic_response = defaultdict(list)
dic_response['d']['DisplayStatusList'] = [{
'DisplayStatusID': 26,
'Name': 'To sell'

It fails with

Traceback (most recent call last): File
"/home/maazza/PycharmProjects/django_test/app_tester/", line
422, in test_save_display_status
'Name': 'To sell', TypeError: list indices must be integers, not str

I wonder what's wrong.


The way you're using this, you should be declaring defaultdict(dict). What's happening right now is you're accessing dic_response['d'], which creates a new list (which should be a dict, but you asked for defaultdict(list) so you're getting a list). Then that new list is being used as new_list['DisplayStatusList'], which is producing the exception you're seeing.