Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of tuples to python dictionary without losing the order

I try to convert a list of tuples to a dictionary but when I do it using the dict() function, the order of the elements is changed:

l = [('id', 2), ('osm_id', 3), ('sourceid', 4), ('notes', 5), ('ref', 6), ('rtenme', 7), ('ntlclass', 8), ('fclass', 9), ('numlanes', 10), ('srftpe', 11), ('srfcond', 12), ('isseasonal', 13), ('curntprac', 14), ('gnralspeed', 15), ('rdwidthm', 16), ('status', 17), ('bridge', 18), ('iso3', 19), ('country', 20), ('last_updat', 21)]

 dict_l = dict(l)
 print (dict_l)

{'fclass': 9, 'status': 17, 'isseasonal': 13, 'bridge': 18, 'sourceid': 4, 'country': 20, 'notes': 5, 'rtenme': 7, 'iso3': 19, 'last_updat': 21, 'gnralspeed': 15, 'osm_id': 3, 'srfcond': 12, 'numlanes': 10, 'srftpe': 11, 'rdwidthm': 16, 'ref': 6, 'id': 2, 'ntlclass': 8, 'curntprac': 14}

What am I missing here?

I also tried to loop through the list of tuples and build the dict manually as:

c = 0
for key, value in display_order_list_sorted:
    display_order_dict_sorted[display_order_list_sorted[c][0]] = display_order_list_sorted[c][1]
    c = c + 1

I faced the same issue.

like image 877
user1919 Avatar asked Aug 31 '25 18:08

user1919


2 Answers

from collections import OrderedDict
l = [('id', 2), ('osm_id', 3), ('sourceid', 4), ('notes', 5), ('ref', 6), ('rtenme', 7), ('ntlclass', 8), ('fclass', 9), ('numlanes', 10), ('srftpe', 11), ('srfcond', 12), ('isseasonal', 13), ('curntprac', 14), ('gnralspeed', 15), ('rdwidthm', 16), ('status', 17), ('bridge', 18), ('iso3', 19), ('country', 20), ('last_updat', 21)]

dict_l = OrderedDict(l)
print (dict_l)
like image 153
Ari Gold Avatar answered Sep 02 '25 10:09

Ari Gold


Python dictionary is not ordered. You need to use OrderedDict.

Gulzar rightfully pointed out in the comments, Python dictionaries are now guaranteed to maintain insertion order starting from Python 3.7

like image 39
Dmitry Yantsen Avatar answered Sep 02 '25 08:09

Dmitry Yantsen