答案 0 :(得分:59)
我使用pip
在python 2.6上安装了ordereddictpip install ordereddict
答案 1 :(得分:22)
根据documentation,对于Python版本2.4或更高版本this code应该使用。还有一些code from Raymond Hettinger,PEP的贡献者之一。这里的代码声称在2.6和3.0下工作,并且是为该提案制作的。
答案 2 :(得分:11)
要为不同版本的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或其他方法),但较新版本将从内置集合模块导入。
答案 3 :(得分:1)
另外,如果您的情况允许,您可以按照自己的方式编程:
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]
第二:[115,101,99,111,110,100]
第四:[102,111,117,114,116,104]
第三:[116,104,105,114,100]
第一:[102,105,114,115,116]首先:[102,105,114,115,116]
第二:[115,101,99,111,110,100]
第三:[116,104,105,114,100]
第四:[102,111,117,114,116,104]
我想,您也可以将有序键嵌入到词典中,因为oDict ['keyList'] = orderedKeys
答案 4 :(得分:1)
您也可以尝试future
,兼容py2-3的代码库:
future
: pip install future
from future.moves.collections import OrderedDict
答案 5 :(得分:0)
给了我:
$ 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
确实