Sorting dict keys

Erik Max Francis max at alcyone.com
Fri Jul 20 18:41:49 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.

.sort returns None.

>>>> b = a.keys()
>>>> b.sort()
> [1, 2, 3]

This snippet is clearly edited, because .sort returns None:

 >>> a = {1:2, 3:4, 2:5}
 >>> b = a.keys()
 >>> b.sort()
 >>> b
[1, 2, 3]

The problem you're having here is that .sort returns None to indicate 
that it mutates the object, rather than returning a new one.  So get the 
keys, sort them, and then move along.

> Works fine, but I would really like it if I could somehow do it in one
> line.

Why is doing it in one line a priority?  Clarity is more important than 
brevity.

Regardless, you can do it in one line with the sorted builtin:

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

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   We must all hang together, or, most assuredly, we will all hang
    separately. -- John Hancock



More information about the Python-list mailing list