What is the best ordered dict implementation in python?

一世执手 提交于 2019-11-28 20:56:06

This one by Raymond Hettinger is a drop-in substitute for the collections.OrderedDict that will appear in Python 2.7: http://pypi.python.org/pypi/ordereddict

The dev version of the collections docs say it's equivalent to what will be in Python 2.7, so it's probably pretty likely to be a smooth transition to the one that will come with Python.

I've put it in PyPI, so you can install it with easy_install ordereddict, and use it like so:

from ordereddict import OrderedDict
d = OrderedDict([("one", 1), ("two", 2)])
DNS

I haven't seen a standard; everyone seems to roll their own (see answers to this question). If you can use the OrderedDict patch from PEP 372, that's your best bet. Anything that's included in the stdlib has a very high chance of being what everyone uses a year or two from now.

collections.OrderedDict should now be widely available, but if performance is concern, you might consider using my package cyordereddict as an alternative. It's a direct port of standard library's OrderedDict to Cython that is 2-6x faster.

Python 2.7 and later have OrderedDict in the collections module, so you should consider that as 'standard'. If its functionality is enough you should probably be using that.

However its implementation approach is minimalistic and if that is not enough you should look at odict by Foord/Larossa or ordereddict (by me) as in that case those are a better fit. Both implementations are a superset of the functionality provided by collections.OrderedDict. The difference between the two being, that odict is pure python and ordereddict a much faster C extension module.

A minimalistic approach is not necessarily better even if it provides all the functionality you need: e.g. collections.OrderedDict did initially have a bug when returning the repr() of a OrderedDict nested in one of its own values. A bug that could have been found earlier, had the subset, the small subset OrderedDict can handle, of unittests of the older ordereddict been used.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!