I would like to create a Data Dictionary using Python from the SQL Server Database. I've written the following code but it gives me the following result,
[OrderedDict([('SystemID', '1'), ('FileID', 1), ('DateTime', None)])]
But I want my result to be as below,
File = { "SystemID": "1", "FileID": "1", "DateTime": None }
I have the following code right now
import pyodbc
import collections
cnxn = pyodbc.connect(trusted_Connection='yes', driver = '{SQL Server}', server = 'localhost', database = 'myDB')
cursor = cnxn.cursor()
cursor.execute("SELECT SystemID, FileID, EventDateTime FROM dbo.File")
rows = cursor.fetchall()
objects_list = []
for row in rows:
d = collections.OrderedDict()
d['SystemID'] = row.SystemID
d['FileID'] = row.FileID
d['DateTime'] = row.EventDateTime
objects_list.append(d)
print objects_list
cnxn.close()
If you use dict(d), you coerce the ordered dictionary to a dict, but there is nothing preventing Python from reordering it, Python
dict
's aren't ordered.Another problem with this is you're looping through the rows, and then just taking the last item, probably since you're developing and intend to move it back into the loop as I show below, but otherwise it doesn't make sense. One shouldn't abuse variables escaping loops in python.
May I suggest:
But then you probably shouldn't be printing in your final product either.