0

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?

bad_keypoints
  • 1,382
  • 2
  • 23
  • 45
  • You're better off creating a 2d list of tuples if you want to preserve order – sshashank124 Mar 22 '14 at 13:42
  • In general, dict keys are not ordered. In another architecture and another Python interpreter, you may get different results. – Selcuk Mar 22 '14 at 13:43
  • @sshashank124 Actually I need to output the results in JSON. So, `dict` – bad_keypoints Mar 22 '14 at 13:45
  • You can't sort dictionaries, as they are just hashmaps at the lower level. They do not need to be ordered. If you find that you need it to be ordered, you generally shouldn't be using one. – anon582847382 Mar 22 '14 at 13:52
  • @AlexThornton hey thanks. Actually I really don't need it to be ordered. Because at the other end, where I'd be accessing it as JSON data, I really wouldn't care. I'd just access the key-value pairs anyways. I guess it was just my OCD nagging at me to have it ordered. – bad_keypoints Mar 22 '14 at 13:59
  • Dictionaries are not ordered. They don't need to be ordered because you access them by keys, so ordering is not relevant. – Burhan Khalid Mar 22 '14 at 14:12
  • Remember: Python Dict has **no** order. – laike9m Mar 22 '14 at 14:16

1 Answers1

1

If you want to perserve the order, you can use an ordered dictionary (OrderedDict) from collections

import collections

rows = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
cols = ['col1', 'col2', 'col3']

res = []
for row in rows:
    res.append(collections.OrderedDict(zip(cols,row)))

The output is:

[OrderedDict([('col1', 1), ('col2', 2), ('col3', 3)]),
 OrderedDict([('col1', 4), ('col2', 5), ('col3', 6)]),
 OrderedDict([('col1', 7), ('col2', 8), ('col3', 9)])]
aha
  • 4,314
  • 4
  • 23
  • 27