[Tutor] Iterating over sorted dictionary keys in one line

Pawel Kraszewski Pawel_Kraszewski at wp.pl
Sun Sep 18 19:40:11 CEST 2005


Dnia niedziela, 18 września 2005 19:20, Marcin Komorowski napisał:

> I know that one of the ways to iterate over sorted dictionary keys is:
>     keylist = dictionary.keys()
>     keylist.sort()
>     for key in keylist:
>         ...

Indeed, 'sort' sorts its argument in-place and returns 'none'. Bur Python 2.4+ 
has a new thing: 'sorted'. This leaves its argument intact and returns a 
sorted copy.

for mykey in sorted(dictionary.keys()):
	# things to do


See this:

Python 2.4.1 (#1, Jun 19 2005, 01:02:56)
[GCC 3.4.4 (Gentoo 3.4.4, ssp-3.4.4-1.0, pie-8.7.8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [4,3,2,1]
>>> print sorted(a) # "sorted" FUNCTION returns sorted list
[1, 2, 3, 4]
>>> a # and original list remains unchanged
[4, 3, 2, 1]
>>> print a.sort() # "sort" METHOD returns nothing
None
>>> a # instead it changes (sorts) its argument
[1, 2, 3, 4]
>>>



Best regards

-- 
 Pawel Kraszewski


More information about the Tutor mailing list