旧版python的OrderedDict

时间:2009-10-24 05:44:34

标签: python

有序词典是非常有用的结构,但遗憾的是,这些词汇仅适用于3.12.7的版本。如何在旧版本中使用有序字典?

6 个答案:

答案 0 :(得分:59)

我使用pip

在python 2.6上安装了ordereddict
pip install ordereddict

答案 1 :(得分:22)

根据documentation,对于Python版本2.4或更高版本this code应该使用。还有一些code from Raymond HettingerPEP的贡献者之一。这里的代码声称在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的代码库:

  1. 通过pip安装future
  2. pip install future

    1. 导入并使用OrderedDict:
    2. from future.moves.collections import OrderedDict

      source

答案 5 :(得分:0)

python2.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

确实