sorting a dictionary

Sean 'Shaleh' Perry shalehperry at attbi.com
Wed Feb 19 03:54:28 EST 2003


On Wednesday 19 February 2003 00:32, user at domain.invalid wrote:
> Suppose I have dictionary (associative arry) with people's names and
> ages, like
>
>      names = {"Bob":27, "Larry":35, "Curly":65, "Moe":66, "Jeff":31,
>               "Guido":34, "Parrot":36}
>
> How can I sort this? And what does the method "names.keys().sort()"
> actually do?

the sort() method affects the list it is called on rather than create a copy.  
In other words:

foo = my_list.sort() # does not work

This is why names.keys().sort() does not work.  You have to use a temporary 
variable.

sorted_names = names.keys()
sorted_names.sort()
for name in sorted_names:
   process(name)





More information about the Python-list mailing list