[英]How do i keep the order of my SQL columns in Python when saving?
If you scroll down a bit you can see this code from gddc return SQL table as JSON in python :如果向下滚动一点,您可以看到 gddc 中的以下代码在 python中将SQL 表作为 JSON 返回:
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)
I just want to keep the order of my columns.我只想保持我的列的顺序。
For example when I print(cols)
I get this:例如,当我print(cols)
我得到这个:
['id', 'Color', 'YCoord', 'Width', 'Height'] # right order
But the columns are saved in a wrong order:但是列以错误的顺序保存:
[{"Color": "#FF99FF","Width"=345, "id"=43, "YCoord"=5784 "Height"=-546}...] # wrong order
The more columns I add, the more random it gets.我添加的列越多,它就越随机。
Python dict
不保存键的顺序,而是使用OrderedDict 。
If I understand You want dictionary to have ordered key.如果我明白你希望字典有排序的键。 It's not possible, because dictionaries are not keeping keys in some order, because keys are used only to access elements.这是不可能的,因为字典没有按某种顺序保存键,因为键仅用于访问元素。 You can always print columns of data using raw column information:您始终可以使用原始列信息打印数据列:
cols = ["column1", "column2", "column3"]
for row in data_from_database:
for col in cols:
print row[col]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.