[Tutor] Iterating over sorted dictionary keys in one line

Kent Johnson kent37 at tds.net
Sun Sep 18 19:30:04 CEST 2005

Marcin Komorowski wrote:
> I know that one of the ways to iterate over sorted dictionary keys is:
>     keylist = dictionary.keys()
>     keylist.sort()
>     for key in keylist:
>         ...
> Is there a way to do this in a single line.  Something like this would 
> be ideal:
>     for key in dictionary.keys().soft():

Python 2.4 adds the sorted() function which returns a sorted copy of a list. You can say
for key in sorted(dictionary.keys()):

and since iterating a dictionary is the same as iterating its keys you can shorten this to
for key in sorted(dictionary):


More information about the Tutor mailing list