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.
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.
sorted(toto.keys())
Should do what you want. The sort method you're using sorts in place and returns None.
sort()
method sort in place, returning none
. You have to use sorted(toto.keys())
which returns a new iterable, sorted.
精彩评论