我使用pip在Python 2.6上安装了ordereddict。
pip install ordereddict
要导入适用于不同版本的Python的OrderedDict类,请考虑以下代码片段:
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
# Now use it from any version of Python
mydict = OrderedDict()
Python 2.6 及以前版本需要安装 ordereddict
(使用pip或其他方法),但更新版本将从内置的collections模块导入。
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]
另外,您可以尝试使用future
,这是一个兼容py2-3的代码库:
future
:pip install future
from future.moves.collections import OrderedDict
在Python 2.6中给了我:
$ pip install ordereddict
Could not find a version that satisfies the requirement from (from versions:)
No matching distribution found for from
但是
$ 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
完成。
对于那些由于某种原因不能依赖用户拥有pip的人来说,这里提供了一个非常糟糕的OrderedDict实现(它是不可变的,具有大多数功能但没有性能提升)。
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)