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}
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 dict
s 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']
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With