我一直在使用以下函数来制作一种“更易读”(据说)格式来从 Oracle 获取数据。这是函数:
def rows_to_dict_list(cursor):
"""
Create a list, each item contains a dictionary outlined like so:
{ "col1_name" : col1_data }
Each item in the list is technically one row of data with named columns,
represented as a dictionary object
For example:
list = [
{"col1":1234567, "col2":1234, "col3":123456, "col4":BLAH},
{"col1":7654321, "col2":1234, "col3":123456, "col4":BLAH}
]
"""
# Get all the column names of the query.
# Each column name corresponds to the row index
#
# cursor.description returns a list of tuples,
# with the 0th item in the tuple being the actual column name.
# everything after i[0] is just misc Oracle info (e.g. datatype, size)
columns = [i[0] for i in cursor.description]
new_list = []
for row in cursor:
row_dict = dict()
for col in columns:
# Create a new dictionary with field names as the key,
# row data as the value.
#
# Then add this dictionary to the new_list
row_dict[col] = row[columns.index(col)]
new_list.append(row_dict)
return new_list
然后我会像这样使用函数:
sql = "Some kind of SQL statement"
curs.execute(sql)
data = rows_to_dict_list(curs)
#
for row in data:
item1 = row["col1"]
item2 = row["col2"]
# Do stuff with item1, item2, etc...
# You don't necessarily have to assign them to variables,
# but you get the idea.
虽然这似乎在不同程度的压力下表现得相当好,但我想知道是否有更有效或“pythonic”的方式来做到这一点。
最佳答案
还有其他改进需要做,但这真的让我大吃一惊:
for col in columns:
# Create a new dictionary with field names as the key,
# row data as the value.
#
# Then add this dictionary to the new_list
row_dict[col] = row[columns.index(col)]
除了效率低下之外,在这种情况下使用 index
还容易出错,至少在同一项目可能在列表中出现两次的情况下是这样。使用 enumerate
代替:
for i, col in enumerate(columns):
# Create a new dictionary with field names as the key,
# row data as the value.
#
# Then add this dictionary to the new_list
row_dict[col] = row[i]
但那只是小土 bean ,真的。这是这个函数的一个更紧凑的版本:
def rows_to_dict_list(cursor):
columns = [i[0] for i in cursor.description]
return [dict(zip(columns, row)) for row in cursor]
让我知道这是否有效。
关于python - 使用 cx_Oracle 制作字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10455863/