简体   繁体   English

旧版python的OrderedDict

[英]OrderedDict for older versions of python

Ordered dictionaries are extremely useful structures, but unfortunately these are quite recent only working in versions from 3.1 and 2.7 . 有序词典是非常有用的结构,但不幸的是,这些最近只适用于3.12.7版本。 How can I use an ordered dictionary in older versions? 如何在旧版本中使用有序字典?

我用pip在python 2.6上安装了ordereddict

pip install ordereddict

According to the documentation , for Python versions 2.4 or later this code should be used. 根据文档 ,对于Python 2.4或更高版本,应使用此代码 There is also some code from Raymond Hettinger , one of the contributors to the PEP . 还有来自 PEP贡献者之一的Raymond Hettinger的一些代码 The code here is claimed to work under 2.6 and 3.0 and was made for the proposal. 声称此处的代码在2.6和3.0下工作,并且是为该提案制作的。

To import a OrderedDict class for different versions of Python, consider this snippet: 要为不同版本的Python导入OrderedDict类,请考虑以下代码段:

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. 早于Python 2.6的版本将需要安装ordereddict (使用pip或其他方法),但较新版本将从内置集合模块导入。

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] 第二:[115,101,99,111,110,100]
fourth : [102, 111, 117, 114, 116, 104] 第四:[102,111,117,114,116,104]
third : [116, 104, 105, 114, 100] 第三:[116,104,105,114,100]
first : [102, 105, 114, 115, 116] 第一:[102,105,114,115,116]

first : [102, 105, 114, 115, 116] 第一:[102,105,114,115,116]
second : [115, 101, 99, 111, 110, 100] 第二:[115,101,99,111,110,100]
third : [116, 104, 105, 114, 100] 第三:[116,104,105,114,100]
fourth : [102, 111, 117, 114, 116, 104] 第四:[102,111,117,114,116,104]

You could embed the ordered keys in your Dictionary too, I suppose, as oDict['keyList'] = orderedKeys 你可以将有序键嵌入你的词典中,我想,因为oDict ['keyList'] = orderedKeys

Also you can try future , py2-3 compatible codebase: 您也可以尝试future py2-3兼容代码库:

  1. install future via pip: 通过点子安装future

pip install future

  1. import and use OrderedDict: 导入和使用OrderedDict:

from future.moves.collections import OrderedDict

source 资源

in python2.6 gave to me: 在python2.6给了我:

$ 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. 没有。

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). 对于那些由于某种原因不能依赖用户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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM