Note: In Python 2.7 use: from __future__ import print_function
to use examples.
In Python, by default, the key and value pairs in a dictionary are stored as hashes, therefore dictionaries do not retain the order in which values were added, and cannot be ordered.
v_Dict ={}
v_Dict["First"] = 99
v_Dict["Second"] = 45
v_Dict["Third"] = 234
print(v_Dict) ## {'Second': 45, 'Third': 234, 'First': 99}
No order at all.
To maintain an ordered dictionary one must use the collection module's "OrderedDict()."
Normally one would declare a dictionary to be ordered like so:
from collections import OrderedDict
v_Dict = OrderedDict()
v_Dict["First"] = 99
v_Dict["Second"] = 45
v_Dict["Third"] = 234
print(v_Dict) ## OrderedDict([('First', 99), ('Second', 45), ('Third', 234)])
An OrderedDict() maintains the order pairs were added.
However, from time to time I find that OrderedDict() is not up to the task. Like here with zip:
from collections import OrderedDict
d_Dict = OrderedDict()
v_Keys = [45, 50, 20]
v_Values = [3.0, 5.0, 2.0]
d_Dict = dict(zip(v_Keys, v_Values))
print(d_Dict) ## {50: 5.0, 20: 2.0, 45: 3.0}
Order is lost again.
To get order back, one must sort the dictionary on the pairs from within OrderedDict(). Like so:
from collections import OrderedDict
v_Keys = [45, 50, 20]
v_Values = [3.0, 5.0, 2.0]
d_Dict = dict(zip(v_Keys, v_Values))
d_Dict = OrderedDict(sorted(d_Dict.items()))
print(d_Dict) ## OrderedDict([(20, 2.0), (45, 3.0), (50, 5.0)])
Order is restored.
I hope someone finds this beneficial.