sorting a dictionary

user at domain.invalid user at domain.invalid
Wed Feb 19 10:28:32 EST 2003


Sean 'Shaleh' Perry wrote:
> 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)
> 
Thanks, but what about the sorting of the dictionary.





More information about the Python-list mailing list