[Python-ideas] `OrderedDict.sort`

Antoine Pitrou solipsis at pitrou.net
Tue Sep 24 14:29:55 CEST 2013


On Tue, 24 Sep 2013 22:13:15 +1000
Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, Sep 24, 2013 at 04:49:20AM -0700, Ram Rachum wrote:
> > What do you think about providing an `OrderedDict.sort` method? I've been 
> > using my own `OrderedDict` subclass that defines `sort` for years, and I 
> > always wondered why the stdlib one doesn't provide `sort`.
> > 
> > I can write the patch if needed.
> 
> I'm not entirely sure why anyone would need an OrderedDict sort method. 
> Ordered Dicts store keys by insertion order. Sorting the keys goes 
> against the purpose of an OrderedDict.

An OrderedDict is basically an associative container with a
well-defined ordering. It's not only "insertion order", because you can
use move_to_end() to reorder it piecewise.
(at some point I also filed a feature request to rotate an OrderedDict:
 http://bugs.python.org/issue17100)

However, sorting would be difficult to implement efficiently with the
natural implementation of an OrderedDict, which uses linked lists.
Basically, you're probably as good sorting the items separately and
reinitializing the OrderedDict with them.

Regards

Antoine.




More information about the Python-ideas mailing list