Sorting dict keys
Will Maier
willmaier at ml1.net
Fri Jul 20 18:47:46 EDT 2007
On Fri, Jul 20, 2007 at 03:27:51PM -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
list's sort() method sorts the list _in_place_:
>>> l = ['spam', 'eggs']
>>> help(l.sort)
Help on built-in function sort:
sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
That means that doesn't return a sorted version of the list you're
working with. Instead, it sorts the list itself.
If you want to return a sorted list, use (duh) sorted:
>>> sorted(l)
['eggs', 'spam', 'spam']
--
[Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/]
More information about the Python-list
mailing list