maazza maazza - 4 months ago 32
Python Question

Correct way to declare a defaultdict

I am currently trying to use a

defaultdict
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/tests.py", line
422, in test_save_display_status
'Name': 'To sell', TypeError: list indices must be integers, not str


I wonder what's wrong.

Answer

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.