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
> > to create another dict. So I think it's almost as good as having a
> > 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:]:
>>> x = 
>>> y = SortableOrderedDict()
>>> y['c'] = 1
>>> y['b'] = 2
>>> y['a'] = 3
['b', 'c', 'a']
SortableOrderedDict([('b', 2), ('c', 1), ('a', 3)])
>>> print(x == list(y.keys()))
FWIW Ram I think you should put the implementation up on PyPI.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas