Josh Gibson
Josh Gibson

Reputation: 22938

What is the best ordered dict implementation in python?

I've seen (and written) a number of implementations of this. Is there one that is considered the best or is emerging as a standard?

What I mean by ordered dict is that the object has some concept of the order of the keys in it, similar to an array in PHP.

odict from PEP 372 seems like a strong candidate, but it's not totally clear that it is the winner.

Upvotes: 6

Views: 7987

Answers (4)

shoyer
shoyer

Reputation: 9603

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.

Upvotes: 2

Anthon
Anthon

Reputation: 76607

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.

Upvotes: 2

sah
sah

Reputation: 476

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)])

Upvotes: 12

DNS
DNS

Reputation: 38189

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.

Upvotes: 8

Related Questions