I'm working with database query results. The output would be like this:
rows = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Which would be, say, 3 rows of table data from the db
And the column names are like this:
cols = ['col1', 'col2', 'col3']
I want make a list of dictionaries out of them, like this:
{'col1':1,'col2':2,'col3':3}
{'col1':4,'col2':5,'col3':6}
So I did this:
res=[]
for row in rows:
res.append(dict(zip(cols,row)))
But res is like this:
[{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}, {'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}]
I can't figure out why the key-value pairs aren't in order by column names. It's not a huge problem, I can sort the dict elements by key names, but how do I get them in order in the first place, without the need to sort them?