Reputation: 141
I have some code that originally looked like this (it's part of a for loop that iterates through the results of a query):
title['name'] += 'x'
I sometimes get the following exception (always on the same row):
<class 'psycopg2.extras.DictRow'>
Traceback (most recent call last):
File "rtk_film_nos.py", line 231, in <module>
main()
File "rtk_film_nos.py", line 150, in main
title['name'] += 'x'
TypeError: list indices must be integers, not str
I changed the code to be more verbose:
foo = title['name']
foo += 'x'
print type(title)
title['name'] = foo
The exception changed to:
<class 'psycopg2.extras.DictRow'>
Traceback (most recent call last):
File "rtk_film_nos.py", line 231, in <module>
main()
File "rtk_film_nos.py", line 150, in main
title['name'] = foo
TypeError: list indices must be integers, not str
If I wrap the code in a try/except it will quite happily print the contents of title['name'].
I'm at a loss as to what I'm doing wrong. It seems that for some reason python (v2.6.6) is deciding to treat the dict as a list but I have no idea why.
Upvotes: 1
Views: 1877
Reputation: 1124188
The DictRow
class is a subclass of list
, and until version 2.3.0 you could not use it to assign to elements by name.
You can work around this by looking up the column index directly:
title[title._index['name']] = foo
or, for your augmented assignment:
title[title._index['name']] += 'x'
Upvotes: 3