OrderedDict for older versions of python

I installed ordereddict on python 2.6 with pip

pip install ordereddict

According to the documentation, for Python versions 2.4 or later this code should be used. There is also some code from Raymond Hettinger, one of the contributors to the PEP. The code here is claimed to work under 2.6 and 3.0 and was made for the proposal.


To import a OrderedDict class for different versions of Python, consider this snippet:

try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

# Now use it from any version of Python
mydict = OrderedDict()

Versions older than Python 2.6 will need to install ordereddict (using pip or other methods), but newer versions will import from the built-in collections module.


Also, you could just program your way around it if your situation allows:

def doSomething(strInput): return [ord(x) for x in strInput]

things = ['first', 'second', 'third', 'fourth']

oDict = {}
orderedKeys = []
for thing in things:
    oDict[thing] = doSomething(thing)
    orderedKeys.append(thing)

for key in oDict.keys():
    print key, ": ", oDict[key]

print

for key in orderedKeys:
    print key, ": ", oDict[key]

second : [115, 101, 99, 111, 110, 100]
fourth : [102, 111, 117, 114, 116, 104]
third : [116, 104, 105, 114, 100]
first : [102, 105, 114, 115, 116]

first : [102, 105, 114, 115, 116]
second : [115, 101, 99, 111, 110, 100]
third : [116, 104, 105, 114, 100]
fourth : [102, 111, 117, 114, 116, 104]

You could embed the ordered keys in your Dictionary too, I suppose, as oDict['keyList'] = orderedKeys