[FIXED] Preserve ordering when consolidating two lists into a dict

Issue

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}

Solution

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']


Answered By - nneonneo
Answer Checked By - Mary Flores (sql.easybugfix Volunteer)

Related Posts

Post a Comment