Sorting dict keys

Jean-Paul Calderone exarkun at divmod.com
Fri Jul 20 18:45:11 EDT 2007


On Fri, 20 Jul 2007 15:27:51 -0700, montyphyton at gmail.com wrote:
>Consider the following:
>>>> a = {1:2, 3:4, 2:5}
>
>Say that i want to get the keys of a, sorted. First thing I  tried:
>
>>>> b = a.keys().sort()
>>>> print b
>None
>
>Doesn't work. Probably because I am actually trying to sort the keys
>of the dictionary without copying them first. If that is the case,
>fine. Next thing I do:
>
>>>> b = a.keys()
>>>> b.sort()
>[1, 2, 3]

This is a mis-observation.  b.sort() does /not/ return [1, 2, 3].
b.sort() returns None.  The sort method of the list type performs
an in-place sort and always returns None.  With that in mind, the
rest of your code snippets might make more sense.

I'll leave it to you to figure out how to jam everything into one
line (or, more realistically, another poster in about 2 seconds,
I'm sure), since I don't really see the value in that exercise
myself.

Jean-Paul



More information about the Python-list mailing list