Discussion about PEP 234: iterators

Alex Martelli aleaxit at yahoo.com
Fri Feb 16 14:39:56 EST 2001


"Russell E. Owen" <owen at astroNOJNK.washington.edu.invalid> wrote in message
news:96jonj$i0e$1 at nntp6.u.washington.edu...
> This is in reaction to the new iterator proposal
> <http://python.sourceforge.net/peps/pep-0234.html>:
>
> My own reaction is "great!" one misgiving: it does not address a very
> common need: to iterate over a dictionary in key-sorted order. Is there
> some variant syntax that could handle this case?
>
> (Better yet, and going out on thin ice here, could this be made the
> default? I realize that's unlikely and may anger some people to even
> suggest it, but I would like to point out that some languages actually
> store dictionaries with their keys ordered, so it's at least technically
> feasible).

One can choose to store mappings using sorted order on keys (that,
for example, is how C++'s standard std::map is specified to work),
but performance for all other tasks can suffer quite substantially
when compared to hash tables.  Python uses dictionaries so widely
that _any_ hit on dictionary performance would not be acceptable.

I would suggest leaving dictionaries alone and supplying another
instance of mapping, based on red-black trees or some variant
thereon, if the sorted-keys requirement is indeed so widespread.


> If this issue cannot be addressed, could we at least get "sort" to
> return the sorted collection, so one could do:
>
> for key in dictionary.keys().sort():

Why not

def sort(adisposablelist):
    adisposablelist.sort()
    return adisposablelist

and then

for key in sort(dictionary.keys()):


Is the syntax-sugar difference so big, after all?


Alex






More information about the Python-list mailing list