sorting a dictionary

Brett Leach brettlea at earthlink.net
Wed Feb 19 23:51:22 EST 2003


To be more plain: You can't sort a dictionary.

On 2/19/03 9:28 AM, in article 3E53A2A0.8090804 at domain.invalid,
"user at domain.invalid" <user at domain.invalid> wrote:

> 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