我有一些最初看起来像这样的代码(它是迭代查询结果的 for 循环的一部分):
title['name'] += 'x'
我有时会遇到以下异常(总是在同一行):
<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
我将代码更改为更详细:
foo = title['name']
foo += 'x'
print type(title)
title['name'] = foo
异常更改为:
<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
如果我将代码包装在 try/except 中,它会很高兴地打印 title['name'] 的内容。
我不知道自己做错了什么。似乎出于某种原因 python (v2.6.6) 决定将 dict 视为列表,但我不知道为什么。
最佳答案
DictRow
类是 list
的子类,并且 until version 2.3.0您不能使用它按名称分配给元素。
您可以通过直接查找列索引来解决此问题:
title[title._index['name']] = foo
或者,对于您的增强作业:
title[title._index['name']] += 'x'
关于Python 认为 psycopg2 DictRow 是列表(至少看起来是这样),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30088254/