[Tutor] sorting dictionary keys?

Kent Johnson kent37 at tds.net
Tue May 13 13:40:30 CEST 2008


On Tue, May 13, 2008 at 7:06 AM, James Hartley <jjhartley at gmail.com> wrote:

>  But if the keys are sorted, I get an error:
>  $ cat test1.py
>  d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 }
>
>  for i in d.keys().sort():
>     print "%s\t%s" % (i, d[i])
>  $ python test1.py
>  Traceback (most recent call last):
>   File "test.py", line 3, in <module>
>     for i in d.keys().sort():

  for i in sorted(d.keys()):
or simply
  for i in sorted(d):
since iterating a dict gives its keys.

The problem is that the inplace sort() returns None.
d.keys() is a (new) list containing the keys
d.keys().sort() gets the list of keys and sorts it, but the value of
the expression is None, so you are essentially writing
  for i in None:
which gives the TypeError you see.

The builtin function sorted() takes any iterable as an argument and
*returns* a sorted sequence so you can use it in an expression.

Kent


More information about the Tutor mailing list