保存时如何保持 SQL 列在 Python 中的顺序?
How do i keep the order of my SQL columns in Python when saving?
如果向下滚动一点,您可以从 g.d.d.c return SQL table as JSON in python:
中看到这段代码
qry = "Select Id, Name, Artist, Album From MP3s Order By Name, Artist"
# Assumes conn is a database connection.
cursor = conn.cursor()
cursor.execute(qry)
rows = [x for x in cursor]
cols = [x[0] for x in cursor.description]
songs = []
for row in rows:
song = {}
for prop, val in zip(cols, row):
song[prop] = val
songs.append(song)
# Create a string representation of your array of songs.
songsJSON = json.dumps(songs)
我只想保持我的专栏顺序。
例如,当我 print(cols)
我得到这个:
['id', 'Color', 'YCoord', 'Width', 'Height'] # right order
但是列的保存顺序有误:
[{"Color": "#FF99FF","Width"=345, "id"=43, "YCoord"=5784 "Height"=-546}...] # wrong order
我添加的列越多,它变得越随机。
Python dict
不保存键的顺序,使用 OrderedDict 代替。
如果我明白你想要字典有有序的键。这是不可能的,因为字典没有按某种顺序保存键,因为键仅用于访问元素。您始终可以使用原始列信息打印数据列:
cols = ["column1", "column2", "column3"]
for row in data_from_database:
for col in cols:
print row[col]
如果向下滚动一点,您可以从 g.d.d.c return SQL table as JSON in python:
中看到这段代码qry = "Select Id, Name, Artist, Album From MP3s Order By Name, Artist"
# Assumes conn is a database connection.
cursor = conn.cursor()
cursor.execute(qry)
rows = [x for x in cursor]
cols = [x[0] for x in cursor.description]
songs = []
for row in rows:
song = {}
for prop, val in zip(cols, row):
song[prop] = val
songs.append(song)
# Create a string representation of your array of songs.
songsJSON = json.dumps(songs)
我只想保持我的专栏顺序。
例如,当我 print(cols)
我得到这个:
['id', 'Color', 'YCoord', 'Width', 'Height'] # right order
但是列的保存顺序有误:
[{"Color": "#FF99FF","Width"=345, "id"=43, "YCoord"=5784 "Height"=-546}...] # wrong order
我添加的列越多,它变得越随机。
Python dict
不保存键的顺序,使用 OrderedDict 代替。
如果我明白你想要字典有有序的键。这是不可能的,因为字典没有按某种顺序保存键,因为键仅用于访问元素。您始终可以使用原始列信息打印数据列:
cols = ["column1", "column2", "column3"]
for row in data_from_database:
for col in cols:
print row[col]