[Python-ideas] `OrderedDict.sort`

Tim Delaney timothy.c.delaney at gmail.com
Tue Sep 24 22:42:19 CEST 2013


On 25 September 2013 04:10, M.-A. Lemburg <mal at egenix.com> wrote:

> On 24.09.2013 17:51, Ram Rachum wrote:
> > I get your point. It's a nice idea. But I think it's slightly less
> elegant
> > to create another dict. So I think it's almost as good as having a
> `.sort`
> > method, but not quite as nice.
>
> You can avoid the temp dict by doing some introspection of
> the arguments and using iterators instead.
>
> > (By the way, couldn't you make the same argument about `list.sort`?)
>
> The use case is different. With list.sort() you don't want to create
> a copy of the list, but instead have the list sort itself, since
> you're not interested in the original order.
>
> You'd only use an OrderedDict to begin with if you're interested in
> the insert order, otherwise you'd start out with a plain dict().


Not quite. As Ram showed, it's perfectly possible to sort an OrderedDict
in-place, which you couldn't do with a normal dict. In which case you're
looking at equivalent semantics as for a list (where items are just added
using append) - using Ram's implementation above:

>>> import collections
>>>
>>> class SortableOrderedDict(collections.OrderedDict):
...     def sort(self, key=None):
...         sorted_keys = sorted(self.keys(), key=key)
...         for key_ in sorted_keys[1:]:
...             self.move_to_end(key_)
...
>>> x = []
>>> x.append('c')
>>> x.append('b')
>>> x.sort()
>>> x.append('a')
>>>
>>> y = SortableOrderedDict()
>>> y['c'] = 1
>>> y['b'] = 2
>>> y.sort()
>>> y['a'] = 3
>>>
>>> print(x)
['b', 'c', 'a']
>>> print(y)
SortableOrderedDict([('b', 2), ('c', 1), ('a', 3)])
>>> print(x == list(y.keys()))
True
>>>

FWIW Ram I think you should put the implementation up on PyPI.

Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130925/34d1c0a0/attachment.html>


More information about the Python-ideas mailing list