[Tutor] Sorting a dictionary in one line?

Terry Carroll carroll@tjc.com
Sun Jan 19 15:59:02 2003


This isn't a practical question; I just want to get a better handle on why
something I tried didn't work.

I want to print a dictionary, sorted by key.   This works:

dict = { 'Kate': 'Bush',
         'Paul': 'McCartney',
         'Debbie': 'Gibson',
         'Faye': 'Wong',
         'David': 'Bowie',
         'Keith': 'Emerson',
         'Tori': 'Amos',
         'John': 'Lennon',
         'Sarah': 'Brightman',
         'Jimmy': 'Buffet'
         }
keylist = dict.keys()
keylist.sort()
for x in keylist:
    print x, dict[x]


In my first attempt, I tried to combine the sort() and keys() calls, right
in the for statement, without using a temporary list, and it doesn't work.
I tried several variations on a theme, but here's a general idea
illustrating what I was attempting:

for x in dict.keys().sort():
    print x, dict[x]

(TypeError: iteration over non-sequence)

My questions:

1) Why doesn't this work? If I understand this right, dict.keys() returns
a list, and lists have a sort() method, which returns a list, which is a
sequence; so why is this an iteration over a non-sequence?

2) Not that it's important to do this in one line, but is it possible?


-- 
Terry Carroll        |
Santa Clara, CA      |   "The parties are advised to chill."
carroll@tjc.com      |       - Mattel, Inc. v. MCA Records, Inc.,
Modell delendus est  |         no. 98-56577 (9th Cir. July 24, 2002)