[Tutor] Iterating over sorted dictionary keys in one line

bob bgailer at alum.rpi.edu
Mon Sep 19 00:33:43 CEST 2005

At 10:30 AM 9/18/2005, Kent Johnson wrote:
>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()):

To be more precise - sorted() operates on any iterable and returns a list.

>and since iterating a dictionary is the same as iterating its keys you can 
>shorten this to
>for key in sorted(dictionary):
>Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list