Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve ordering when consolidating two lists into a dict

I am using mysqldb to connect to mysql database and I get the metadata/columns in a variable and data/row in another. Now I have to consolidate the list and tuple into a dict and also preserve the order. I know that dicts are orderless but is there any alternative to this?

cursor.description = ['userid', 'cid', 'mid', 'did', 'msid']
data = (29L, 35L, None, '', None)

result = {}
for i in data:
    result.update = dict(zip(cols, i))

Expected result

result = {'userid': 29L, 'cid': 35L, 'mid': None, 'did': '', 'msid': None}
like image 621
ronak Avatar asked Mar 12 '13 21:03

ronak


2 Answers

Use an OrderedDict:

from collections import OrderedDict

result = OrderedDict(zip(cursor.description, data))

Example:

>>> from collections import OrderedDict
>>> cols = ['userid', 'cid', 'mid', 'did', 'msid']
>>> data = (29L, 35L, None, '', None)
>>> result = OrderedDict(zip(cols, data))
>>> result
OrderedDict([('userid', 29L), ('cid', 35L), ('mid', None), ('did', ''), ('msid', None)])
>>> result['userid']
29L
>>> result['cid']
35L
>>> list(result)
['userid', 'cid', 'mid', 'did', 'msid']

From CPython 3.6 onwards, and Python 3.7 onwards, regular dicts are sorted by insertion order, so you can use dict here instead of OrderedDict if you know your code will run under a suitable version.

Python 3.7+ only (or Python 3.6 under CPython):

>>> cols = ['userid', 'cid', 'mid', 'did', 'msid']
>>> data = (29, 35, None, '', None)
>>> result = dict(zip(cols, data))
>>> result
{'userid': 29, 'cid': 35, 'mid': None, 'did': '', 'msid': None}
>>> result['userid']
29
>>> result['cid']
35
>>> list(result)
['userid', 'cid', 'mid', 'did', 'msid']
like image 141
nneonneo Avatar answered Oct 15 '22 02:10

nneonneo


forget the dict

>>> cols=['userid', 'cid', 'mid', 'did', 'msid']
>>> data = (29L, 35L, None, '', None)
>>> zip(cols,data)
[('userid', 29L), ('cid', 35L), ('mid', None), ('did', ''), ('msid', None)]

If you have lots of result sets then set up an array first and append to it

>>> myarray.append(zip(cols,data))
like image 27
Vorsprung Avatar answered Oct 15 '22 03:10

Vorsprung