tags:

views:

139

answers:

3

Hi,

I'm new to Python and can't understand why a thing like this does not work. I can't find the issue raised elsewhere either.

toto = {'a':1, 'c':2 , 'b':3}
toto.keys().sort()           #does not work (yields none)
(toto.keys()).sort()         #does not work (yields none)
eval('toto.keys()').sort()   #does not work (yields none)

Yet if I inspect the type I see that I invoke sort() on a list, so what is the problem..

toto.keys().__class__     # yields <type 'list'>

The only way I have this to work is by adding some temporary variable, which is ugly

temp = toto.keys()
temp.sort()

What am I missing here, there must be a nicer way to do it.

+7  A: 

sort() sorts the list in place. It returns None to prevent you from thinking that it's leaving the original list alone and returning a sorted copy of it.

MatrixFrog
I guess that makes sense. thanks.
nicolas
+6  A: 
sorted(toto.keys())

Should do what you want. The sort method you're using sorts in place and returns None.

CTT
aah! beat me to it!
Shrikant Sharat
Alternatively, use `sorted(toto.iterkeys())` in case the dict is large to prevent the creation and destruction of the unsorted keys list.
Chris Lutz
In Python 2.6 and 3.x you can just use `sorted(toto)` to get the same result. In fact, the use of `.keys()` is deprecated.
jathanism
+1  A: 

sort() method sort in place, returning none. You have to use sorted(toto.keys()) which returns a new iterable, sorted.

Stefano Borini
Is there any way to retain a similar postfix notation ?Like for len, one can use alist.__len__() instead of len(alist)
nicolas
if you are calling l.__len__() it means that you are doing it wrong.
Stefano Borini
Ok thanks for the advice. I have a hard time not using postfix notation though like alist.map().filter().sort().map().len()it puts the operation close to its arguments, so its really handy, instead of operation1(operation2(operation3(arg, arg3), arg2),arg1)
nicolas
what you want to do is called method chaining. it's a pattern which is not implemented by any standard python type.
Stefano Borini