sorteddict PEP proposal [started off as orderedict]

Paul Hankin paul.hankin at gmail.com
Tue Sep 25 15:28:29 EDT 2007


On Sep 25, 7:58 pm, Steven Bethard <steven.beth... at gmail.com> wrote:
> > Paul Hankin wrote:
> > ...
> > class sorteddict(dict):
> >     "A sorted dictionary"
> >     def __init__(self, arg=None, cmp=None, key=None, reverse=False):
> >         if arg:
> >     ...
>
> With this is the implementation, I'm definitely -1. Not because it's a
> bad implementation, but because if the iteration is always doing a sort,
> then there's no reason for a separate data structure. Just use sorted()
> directly on a regular dict. That has the advantage of being much more
> obvious about where the expensive operations are::
>
>      for key in sorted(d, ...):
>          ... whatever you want to do ...
>
> IMHO, the only reason to introduce a sorteddict() is if it minimizes the
> cost of sorting the keys.

I disagree with your reason for introducing a sorteddict - the main
reason should be if it makes code that uses it simpler and more
readable, with efficiency (within reasonable limits) being of
secondary importance. Unfortunately for sorteddict, your code is
simpler and more explicit for most obvious use cases.

But, with Bill's cached sorted key list it'll be reasonably efficient,
and it's likely possible to update the sorted cache more efficiently
than resorting if there's only been a small number of insertions since
the last sort, but I haven't the time to do a thorough job.

--
Paul Hankin




More information about the Python-list mailing list