Python旧版本的OrderedDict

57

有序字典是非常有用的数据结构,但不幸的是,它们只适用于 3.12.7 版本的 Python,那么在旧版本中如何使用有序字典呢?


有序字典对你有用吗?你能帮我检查一下这个页面末尾的代码吗? - harris
7个回答

60

我使用pip在Python 2.6上安装了ordereddict。

pip install ordereddict

你能告诉我如何使用吗?我尝试了easy_install ordereddict,但不太确定用法。 - ThinkCode
12
从ordereddict模块导入OrderedDict。[通过一些谷歌搜索得到的结果] - ThinkCode
在Windows上安装PIP:https://dev59.com/questions/Bm445IYBdhLWcg3wq8FY - DanMan

22

根据文档,对于Python 2.4或更高版本,请使用这段代码。另外还有来自Raymond Hettinger的一些代码,他是PEP的贡献者之一。这里的代码声称可以在2.6和3.0下工作,并且是为该建议而制作的。


软件包"ordereddict"可以为您实现这一点。正如Arthur Ulfeldt所指出的那样,您可以使用Pip进行安装 :) - UsAndRufus
@UsAndRufus,OrderedDict 没有生效。 - harris

12

要导入适用于不同版本的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模块导入。


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] 你也可以将有序的键嵌入到字典中,如oDict['keyList'] = orderedKeys。

1

另外,您可以尝试使用future,这是一个兼容py2-3的代码库:

  1. 通过pip安装future

pip install future

  1. 导入并使用OrderedDict:

from future.moves.collections import OrderedDict

source


0

在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

完成。


-1

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接