Sorting dict keys

montyphyton at gmail.com montyphyton at gmail.com
Sat Jul 21 01:34:34 CEST 2007


On 21 srp, 00:47, Duncan Smith <buzz... at urubu.freeserve.co.uk> wrote:
> montyphy... 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]
>
> > Works fine, but I would really like it if I could somehow do it in one
> > line. As the problem seems to be copying the object, i try the
> > following:
>
> >>>>import copy
> >>>>b = copy.copy(a.keys()).sort()
> >>>>print b
>
> > None
>
> > Hmmm, why doesn't it work? Also,
>
> >>>>b = copy.deepcopy(a.keys()).sort()
> >>>>print b
>
> > None
>
> > (not that I thought that deepcopy will work since shallow didn't, I
> > understand the difference :) )
> > Obviously, I am missing something here. What am I thinking wrong? Why
> > doesn't copying the object work?
> > Thanks for all the help
>
> sort() sorts a list in place and returns None.  For a one-liner:
>
> >>> a = {1:2, 3:4, 2:5}
> >>> b = sorted(a.keys())
> >>> b
>
> [1, 2, 3]
>
> Duncan

Thanks, this is what I was looking for. I know that .sort() sorts the
list in-place (the snippet I posted was written in a hurry, not pasted
-- I apologise for that). In fact, this is exactly what puzzles me.
copy.copy returns a new object:

>>> copy.copy(a.keys())
[1,2,3]

Then why doesn't copy.copy(a.keys()).sort() work??
Thanks to everyone who replied!




More information about the Python-list mailing list