[Tutor] Keeping Dictonary Entries Ordered

Kent Johnson kent37 at tds.net
Thu Feb 12 13:04:12 CET 2009


On Thu, Feb 12, 2009 at 4:25 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:

> Thats tricky! Dictionaries are not sorted and do not retain insertion order.

> But you need to have an order that will work with sorted().
> Its not just the order you add items to the dict. To store an
> arbitrary order I suspect you would need to maintain a
> secondary list with the keys in the order of insertion.
> The most reliable way to dop that would be to subclass
> dict. Somebody may already have done that so its worth
> a google...

In fact this is planned for inclusion in Python 2.7:
http://www.python.org/dev/peps/pep-0372/

The PEP lists several implementations including one with the specified API:
http://dev.pocoo.org/hg/sandbox/raw-file/tip/odict.py

Kent


More information about the Tutor mailing list