Python 认为 psycopg2 DictRow 是列表(至少看起来是这样)

Python thinks that psycopg2 DictRow is list (At least that's what it looks like)

我有一些代码最初看起来像这样(它是遍历查询结果的 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) 决定将字典视为列表,但我不知道为什么。

DictRow class 是 list 的子 class,并且 until version 2.3.0 您不能使用它按名称分配给元素。

您可以通过直接查找列索引来解决此问题:

title[title._index['name']] = foo

或者,对于您的扩充作业:

title[title._index['name']] += 'x'