Reputation: 7183
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.
Upvotes: 0
Views: 1749
Reputation: 43447
You created a dictionary where each key has a list as its value, but then you tried to access one of those list items using string index...
Looks like you wanted to create a default dictionary of dictionaries...
>>> from collections import defaultdict
>>> dic_response = defaultdict(dict)
>>> dic_response['d']['DisplayStatusList'] = [{'DisplayStatusID': 26, 'Name': 'To sell'}]
>>> dic_response
defaultdict(<type 'dict'>, {'d': {'DisplayStatusList': [{'DisplayStatusID': 26, 'Name': 'To sell'}]}})
Upvotes: 4
Reputation: 36688
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.
Upvotes: 2