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.
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)
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
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