OrderedDict for older versions of python

Question:

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?

Asked By: Casebash

||

Answers:

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.

Answered By: Casebash

I installed ordereddict on python 2.6 with pip

pip install ordereddict
Answered By: Arthur Ulfeldt

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.

Answered By: Mike T

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.

Answered By: noragen

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)
Answered By: vitiral

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

Answered By: user6332699

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

Answered By: juggernaut
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.