3

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.

2
  • I'm not sure about the solution but aren't dictionary keys unordered? Commented Jan 31, 2010 at 5:17
  • 1
    @Shraptnel: you are correct. The OP is placing the keys into a list and sorting that list. Commented Jan 31, 2010 at 5:30

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

6
sorted(toto.keys())

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

2 Comments

Alternatively, use sorted(toto.iterkeys()) in case the dict is large to prevent the creation and destruction of the unsorted keys list.
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.
1

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

4 Comments

Is there any way to retain a similar postfix notation ? Like for len, one can use alist.__len__() instead of len(alist)
if you are calling l.__len__() it means that you are doing it wrong.
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)
what you want to do is called method chaining. it's a pattern which is not implemented by any standard python type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.