a question regarding conciseness
Christophe Delord
christophe.delord at free.fr
Wed Feb 20 15:48:52 EST 2002
Python help says :
---
Help on built-in function sort:
sort(...)
L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) ->
-1, 0, 1
---
sort returns nothing, it just sorts the list :
>>> print [].sort()
None
Writting a function to sort lists may not be efficient :
def my_sort(L):
L2 = L[:]
L2.sort()
return L2
X = [...]
for x in my_sort(X):
....
Christophe.
Rajarshi Guha wrote:
> Hi,
> I have a dictionary and would like to loop over the elements in sorted
> order.
> The dictionary is of the form:
>
> {'1':'option1', '2':'option2', '3':'option3'}
>
> However when I use:
>
> for i in d.keys().sort():
> do something
>
> I get:
>
> Traceback (innermost last):
> File "<stdin>", line 1, in ?
> TypeError: loop over non-sequence
>
> But I know that d.keys() returns a list to which the sort() function should
> be applicable.
>
> When I do:
>
> k = d.keys()
> k.sort()
> for i in k:
> do something
>
> it works fine.
> Why can't I use d.keys().sort() directly? And is there any other more
> concise (elegent?) way to loop over sorted dictionary keys?
>
> TIA,
>
>
More information about the Python-list
mailing list