Sorting dict keys

Duncan Smith buzzard at urubu.freeserve.co.uk
Fri Jul 20 18:47:56 EDT 2007


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]
> 
> 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



More information about the Python-list mailing list