[Python-ideas] `OrderedDict.sort`

Ram Rachum ram.rachum at gmail.com
Tue Sep 24 14:27:08 CEST 2013


I think that your mistake is defining OrderedDict as a dict sorting by 
insertion order. I see no reason to define it that way, and the fact that 
insertion order is the default is not a reason in my opinion. It's just a 
dict with an order, and I see no reason to not let users move elements 
about as they wish. Yes, I'm aware that the documentation defined 
OrderedDict your way too; I still think it's a pointless restriction. 

Regarding examples:

I've used my `OrderedDict.sort` at least 10 times. Just today I've used it 
again. I was putting three items in an ordrered dict, with keys 'low', 
'medium' and 'high'. I wanted to have them sorted as 'low', 'medium' and 
'high' but the insertion order was different because of the algorithm that 
calculated them. (Also not all 3 items were guaranteed to exist, I wanted 
to sort those that existed.)

So I created an OrderedDict of my subclass and called `.sort`.

I'm sure you can think of a bunch more examples, if not I can give them to 
you.

On Tuesday, September 24, 2013 3:13:15 PM UTC+3, Steven D'Aprano 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. 
>
> I can understand a request for a SortedDict, that keeps the keys in 
> sorted order as they are deleted or inserted. I personally don't have 
> any need for one, since when I need the keys in sorted order I just 
> sort them on the fly: 
>
> for key in sorted(dict): 
>     ... 
>
>   
> but in any case, that's a separate issue from sorting an OrderedDict. 
> Can you explain the use-case for why somebody might want to throw away 
> the insertion order and replace with sorted order? 
>
>
>
> -- 
> Steven 
> _______________________________________________ 
> Python-ideas mailing list 
> Python... at python.org <javascript:> 
> https://mail.python.org/mailman/listinfo/python-ideas 
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130924/b415a06f/attachment.html>


More information about the Python-ideas mailing list