[Tutor] Sorting a dictionary in one line?

alan.gauld@bt.com alan.gauld@bt.com
Mon Jan 20 06:35:03 2003


> for x in dict.keys().sort():
>     print x, dict[x]

> My questions:
> 1) Why doesn't this work? If I understand this right, 
> dict.keys() returns a list, 

correct

> and lists have a sort() method, which returns a list, 

Not quite. sort() sorts the list *in place* and does not 
return a new list.

try:

>>> [3,1,2].sort()
>>> # note no list printed
>>> l = [3,1,2]
>>> l
[3,1,2]
>>> l.sort()
>>> # again no output
>>> l
[1,2,3]
>>> # the original list is now sorted

> 2) Not that it's important to do this in one line, but is it possible?

Only by being very obtuse!

for n in [dict.keys() for x in [1] if dict.keys().sort != None][0]:
   print n, dict[n]

But I'm sure theres an easier way...

Personally I'd just go with the two lines.

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/