Alphabetized dictionary listings
Quinn Dunkan
quinn at pfennig.ugcs.caltech.edu
Wed Nov 17 19:51:29 EST 1999
On Wed, 17 Nov 1999 14:23:51 GMT, Ken Power <iam at not.you> wrote:
>Why does this occur? More to the point, how can I have the print-out
>be in alphabetical order?
>
>>>> myList = ['Abel', 'Dexter', 'Francis', 'Matthew', 'Samantha', 'Tyrone']
>>>> myDict = {}
>>>> for name in myList:
> myDict[name] = 0
>
>
>>>> for key in myDict.keys():
> print key
>
>
>Tyrone
>Samantha
>Francis
>Abel
>Matthew
>Dexter
Both of your examples assume there is some sort of order to a dictionary...
there isn't. The documentation for the keys() method in the reference manual
at 2.1.6 says: "Keys and values are listed in random order." This has to do
with the way dictionaries are implemented internally.
sort() to the rescue! The usual idiom for what you want is:
k = dict.keys()
k.sort()
for i in k:
print i
If you're wondering why you can't just do
for i in dict.keys().sort():
print i
check out faq 6.20
python-doesn't-allow-!s-in-identifiers-ly y'rs
More information about the Python-list
mailing list