a question regarding conciseness

Rajarshi Guha rxg218 at psu.edu
Wed Feb 20 14:51:41 EST 2002


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,

-- 
-------------------------------------------------------------------
Rajarshi Guha                  | email: rajarshi at presidency.com
417 Davey Laboratory           | web  : http:// www.jijo.cjb.net
Dept. Of Chemistry             | ICQ  : 123242928
Pennsylvania State University  | AIM  : LoverOfPanda
-------------------------------------------------------------------
GPG Fingerprint: DCCB 4D1A 5A8B 2F5A B5F6  1F9E CDC4 5574 9017 AF2A 
Public Key     : http://pgp.mit.edu/
-------------------------------------------------------------------
CChheecckk yyoouurr dduupplleexx sswwiittcchh..




More information about the Python-list mailing list