OrderedDict适用于较老版本的python
有序的字典是非常有用的结构,但不幸的是,这些是最近才在3.1和2.7的版本中工作。 如何在旧版本中使用有序字典?
我用pip在python 2.6上安装了ordereddict
pip install ordereddict
根据文档 ,对于Python版本2.4或更高版本,应该使用这个代码 。 还有一些来自 PEP的贡献者之一Raymond Hettinger的代码 。 这里的代码被声称在2.6和3.0下工作,并被提出。
要为不同版本的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或其他方法),但是更新的版本将从内置集合模块中导入。
另外,如果你的情况允许,你可以编程:
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]
你可以在你的字典中embedded有序的键,我想,作为oDict ['keyList'] = orderedKeys
在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
没有。
对于那些因为某些原因而不能依赖用户的用户来说,这是OrderedDict的一个非常糟糕的实现(它是不可变的,具有大部分的function,但是没有任何性能提升)。
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)