Keep order when merging two lists in dict

I use mysqldb to connect to mysql database and I get metadata / columns in a variable and data / row in another. Now I need to consolidate the list and tuple in a dict, and also save the order. I know that dictations are carefree, but is there an 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} 
+5
source share
3 answers

Use 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'] 
+10
source

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 many result sets, first set the array and append

 >>> myarray.append(zip(cols,data)) 
+1
source

from the collection of imports OrderedDict new_odered_dict = OrderedDict (zip (list1, list2)) print new_ordered_dict

0
source

Source: https://habr.com/ru/post/1468840/


All Articles