"for k in keys().sort()" -- Beyond the FAQ

Randall Hopper aa8vb at yahoo.com
Thu Dec 2 16:40:10 EST 1999


     I read the FAQ, and while it makes sense, Python's normal bevity
leaves me wondering why I can't do:

        ---------------------------------
        for key in sort( dict.keys() )
          ...
        ---------------------------------

rather than use 3 lines of slightly less clear:

        ---------------------------------
        keys = dict.keys()
        keys.sort()
        for key in keys:
           ...
        ---------------------------------

Is there no built-in sort function that operates on a sequence and produces
a new list?  

If you want this behavior, do you need to define your own sort function:

       def sort(l): l2 = l[:]; l2.sort(); return l2
       for key in sort( dict.keys() ):
          ...

...or is there one lying around in the standard libraries?  A shallow copy
is just fine.

     Any insights appreciated.

-- 
Randall Hopper
aa8vb at yahoo.com









 |6.20. Why doesn't list.sort() return the sorted list?
 |
 |...list.sort() sorts the list in place....
 |
 |As a result, here's the idiom to iterate over the keys of a dictionary in
 |sorted orted:
 |
 |        keys = dict.keys()
 |        keys.sort()
 |        for key in keys:
 |                ...do whatever with dict[key]...
 |




More information about the Python-list mailing list