【问题标题】:How do i keep the order of my SQL columns in Python when saving?保存时如何在 Python 中保持 SQL 列的顺序?
【发布时间】:2016-08-02 14:00:22
【问题描述】:

如果您向下滚动一点,您可以从 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

我添加的列越多,它就越随机。

【问题讨论】:

  • 字典未排序,请将song = {} 替换为song = OrderedDict()。您需要在脚本顶部from collections import OrderedDict
  • 这对我来说既快捷又简单。非常感谢!

标签: python sql-server json pyodbc


【解决方案1】:

Python dict 不保存键的顺序,改用OrderedDict。

【讨论】:

    【解决方案2】:

    如果我理解您希望字典具有有序键。这是不可能的,因为字典没有按某种顺序保存键,因为键仅用于访问元素。您始终可以使用原始列信息打印数据列:

    cols = ["column1", "column2", "column3"]
    for row in data_from_database:
        for col in cols:
            print row[col]
    

    【讨论】:

      猜你喜欢
      • 2016-05-23
      • 1970-01-01
      • 2022-12-24
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多