sorting a dictionary

Brett Leach brettlea at earthlink.net
Wed Feb 19 10:22:40 EST 2003


The order of items in a dictionary is arbitrary. Remember, you are trying to
access the value part of the key:value pair only through the key. If you
want to order the keys, you need a list of those keys.

names.keys()  <--- returns a list of the keys of the dictionary.

names.keys().sort() <--- sorts the list of keys but doesn't return anything.

Thus, if you then do names.keys() again, expecting a sorted list, you don't
get the result of the previous sort, but a new list of keys taken from the
dictionary.

If you want a sorted list of keys returned you might do it like this:

MyKeys = names.keys()
MyKeys.sort()

On 2/19/03 2:32 AM, in article b2vf5p$bg$1 at ctb-nnrp2.saix.net,
"user at domain.invalid" <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?
> 





More information about the Python-list mailing list