简体   繁体   English

保存时如何在 Python 中保持 SQL 列的顺序?

[英]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.

相关问题 如何防止我的 Python 程序在我的 SQL 服务器上使用过多的 memory? - How do I keep my Python program from using too much memory on my SQL Server? 如何在Python中保持列表中排序数字的顺序相同 - How do I keep the order of sorted numbers in a list the same in Python 在python中保存来自html表单的输入值时,为什么仍然收到非类型错误? - Why do I keep receiving a non type error when saving input value from html form in python? 如何保持要依序添加到python列表的项目-输入顺序 - How do I keep items that are being appended to a python list in order - order of input 如何保持 Python function 的精度? - How do I keep the precision in my Python function? 如何按升序显示我的Sql数据? - How Do I Display My Sql Data In Ascending Order? 如何在将 function 应用到 - How do I keep the other columns of my pandas dataframe while appling a function to two columns in 运行python代码时,如何在命令promt中并列显示我的列? - How do i get my columns to display side by side in the command promt when running python code? 如何使用Python反转数据框中的行顺序,但在将索引保存到另一个数据框中时不反转索引 - How to reverse the order of rows in my dataframe using Python, But not reverse the index when saving it into another dataframe 我正在尝试按月顺序保存我的 csv 文件,例如 May、jun 等,并尝试使用 python 更改顺序,但无法做到这一点 - I'm trying to keep my csv files in monthly order like may, jun etc and trying to change the order with python, but unable to do that
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM