Sorting a dictionary

J. Cliff Dyer jcd at
Fri May 15 19:20:33 CEST 2009

On Fri, 2009-05-15 at 09:57 -0700, Tobiah wrote:
> On Tue, 12 May 2009 14:17:54 +0200, Jaime Fernandez del Rio wrote:
> > This one I think I know... Try with:
> > 
> > for k in sorted(word_count) :
> >     print k,"=",word_count[k]
> > 
> > You need to do the sorting before iterating over the keys...
> Isn't that what's happening here?  I read this as the
> 'sorted' function iterating over the keys in word_count,
> then passing that sorted list to the 'for' loop, for a
> second iteration over the sorted pairs.
> No?
> Tobiah

The code and the description you are responding to are by the same
poster.  The OP posted something quite different.


The for statement, which is the line ending with ":" has all the control
over what order elements get processed in.  Compare the following cases:

>>> for x in ['hat', 'socks', 'shirt', 'pants']:
...     print sorted(x)

In this case, each element of the list gets sorted.  That is, the
letters of each string are put in alphabetical order.  But they are
processed in the order they appeared in the list.  If you want to
process the elements of the list in alphabetical order, you have to sort
the list itself:

>>> for x in sorted(['hat', 'socks', 'shirt', 'pants']):
...     print x


More information about the Python-list mailing list