OrderedDict for older versions of python

Python

Python Problem Overview


Ordered dictionaries are extremely useful structures, but unfortunately these are quite recent only working in versions from 3.1 and 2.7. How can I use an ordered dictionary in older versions?

Python Solutions


Solution 1 - Python

I installed ordereddict on python 2.6 with pip

pip install ordereddict

Solution 2 - Python

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.

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

Also you can try future, py2-3 compatible codebase:

  1. install future via pip:

pip install future

  1. import and use OrderedDict:

from future.moves.collections import OrderedDict

source

Solution 6 - Python

in python2.6 gave to me:

$ pip install ordereddict
  Could not find a version that satisfies the requirement from (from versions:)
No matching distribution found for from

but

$ easy_install ordereddict
install_dir /usr/local/lib/python2.6/dist-packages/
Searching for ordereddict
Reading http://pypi.python.org/simple/ordereddict/
Best match: ordereddict 1.1
Downloading https://pypi.python.org/packages/source/o/ordereddict/ordereddict-1.1.tar.gz#md5=a0ed854ee442051b249bfad0f638bbec
Processing ordereddict-1.1.tar.gz
Running ordereddict-1.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-lYgPE3/ordereddict-1.1/egg-dist-tmp-GF2v6g
zip_safe flag not set; analyzing archive contents...
Adding ordereddict 1.1 to easy-install.pth file

Installed /usr/local/lib/python2.6/dist-packages/ordereddict-1.1-py2.6.egg
Processing dependencies for ordereddict
Finished processing dependencies for ordereddict

did.

Solution 7 - Python

For those who can't depend on the user having pip for some reason, here is a really terrible implementaiton of OrderedDict (it is immutable, has most of the features but none of the performance boost).

class OrderedDict(tuple):
    '''A really terrible implementation of OrderedDict (for python < 2.7)'''
    def __new__(cls, constructor, *args):
        items = tuple(constructor)
        values = tuple(n[1] for n in items)
        out = tuple.__new__(cls, (n[0] for n in items))
        out.keys = lambda: out
        out.items = lambda: items
        out.values = lambda: values
        return out

    def __getitem__(self, key):
        try:
            return next(v for (k, v) in self.items() if k == key)
        except:
            raise KeyError(key)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCasebashView Question on Stackoverflow
Solution 1 - PythonArthur UlfeldtView Answer on Stackoverflow
Solution 2 - PythonCasebashView Answer on Stackoverflow
Solution 3 - PythonMike TView Answer on Stackoverflow
Solution 4 - Pythonuser6332699View Answer on Stackoverflow
Solution 5 - PythonjuggernautView Answer on Stackoverflow
Solution 6 - PythonnoragenView Answer on Stackoverflow
Solution 7 - PythonvitiralView Answer on Stackoverflow