为什么(dictionary.keys())。sort()在python中不起作用?

时间:2010-01-31 05:13:49

标签: python sorting

我是Python的新手,无法理解为什么这样的东西不起作用。 我也找不到其他地方提出的问题。

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)

然而,如果我检查类型,我看到我在列表上调用sort(),那么问题是什么..

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

我有这个工作的唯一方法是添加一些临时变量,这是丑陋的

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

我在这里缺少什么,必须有一个更好的方法来做到这一点。

3 个答案:

答案 0 :(得分:7)

sort()对列表进行排序。它会返回None,以防止您认为它单独留下原始列表并返回它的已排序副本。

答案 1 :(得分:7)

sorted(toto.keys())

应该做你想做的事。您正在使用的排序方法就地排序并返回无。

答案 2 :(得分:1)

sort()方法排序到位,返回none。您必须使用sorted(toto.keys())返回一个新的iterable,已排序。