Sorting dict keys

montyphyton at gmail.com montyphyton at gmail.com
Sat Jul 21 00:27:51 CEST 2007


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




More information about the Python-list mailing list