On Tue, May 13, 2008 at 7:06 AM, James Hartley <[EMAIL PROTECTED]> 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 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor