list字典输出不是我所期望的

问题描述 投票:0回答:1

我尝试从py manage.py shell加载数据

使用此代码

def makeDictFactory(cursor):
    columnNames = [d[0] for d in cursor.description]
    def createRow(*args):
        return dict(zip(columnNames, args))
    return createRow 

import cx_Oracle
dsn_tns = cx_Oracle.makedsn('', '', sid='') 
conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns) 
c = conn.cursor() 
c.execute("select table_name from all_tables")
c.rowfactory = makeDictFactory(c)
c.fetchall()

我想要的输出是{a:b,c:d},但是当我执行c.fetchall()时,它变成[{a:b},{c:d}],当我把后端中的代码,并希望将其显示在前端,它将返回错误,例如不可哈希类型dict,不可哈希类型列表或上下文必须是dict或list

我该怎么办?

django cx-oracle
1个回答
0
投票

cursor.fetchall()将使用此方法返回字典的list。这是预期的。如果您想独立处理每一行,那么执行以下操作可能更有意义:

for rowDict in c:
    do_something_with_row_dict(rowDict)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.