[Tutor] Re: Sorting a dictionary in one line?

Derrick 'dman' Hudson dman@dman.ddts.net
Mon Jan 20 18:13:22 2003


--9amGYk9869ThD9tj
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sun, Jan 19, 2003 at 11:13:50PM +0100, Magnus Lycka wrote:
| At 12:56 2003-01-19 -0800, Terry Carroll wrote:
[...]
| >1) Why doesn't this work? If I understand this right, dict.keys() returns
| >a list, and lists have a sort() method, which returns a list, which is a
| >sequence; so why is this an iteration over a non-sequence?
|=20
| No. .sort() returns None!
|=20
| >>> a =3D [3,4,2,1]
| >>> print a.sort()
| None
| >>> print a
| [1, 2, 3, 4]
|=20
| Lists can obviously be very big. For that reason it's important
| that we are able to perform sorts without having to duplicate
| the list. Thus .sort() modifies the original list, not a copy of
| it. The .sort() method could still have had a "return self" in
| the end as a convenience, but it doesn't. The thing is that if
| we wrote "sortedList =3D myList.sort()" it would be very confusing
| to discover that "myList" had become sorted in the operation. For
| that reason .sort() returns None. You need to do:
|=20
| sortedList =3D myList; sortedList.sort()
|=20
| Now there is no ambiguity.

Just be aware that in the above two lines of code, "both" lists are
sorted because the two names are really references to the same mutable
object.  If you want to have a sorted and unsorted version of the
list, make a copy :

    sortedList =3D myList[:]
    sortedList.sort()

-D

--=20
No harm befalls the righteous,
but the wicked have their fill of trouble.
        Proverbs 12:21
=20
http://dman.ddts.net/~dman/

--9amGYk9869ThD9tj
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj4sgh8ACgkQO8l8XBKTpRT89ACgoIov3xkNu7/pRok8nOla9iTF
gssAoJuXk0IcGf0IDh9kNamIV4lHNSDe
=ZUeM
-----END PGP SIGNATURE-----

--9amGYk9869ThD9tj--