Is it possible to sort a dictionary?

Dave LeBlanc whisper at oz.net
Mon Mar 26 13:51:32 EST 2001


How about:

# prints the elements of myDictionary in sort order
# error handling needed (myKeys != none for example)
myKeys = myDictionary.keys()
myKeys.sort()
for key in myKeys:
	print myDictionary[key]

Dave LeBlanc

On Mon, 26 Mar 2001 00:54:19 +0200, Rikard Bosnjakovic
<rikbo716 at student.liu.se> wrote:

>Victor Louie wrote:
>
>> I was just wondering if anyone knows how to sort a dictionary by
>> value...since the dictionary is <key: value> and where my value is a list.
>
>You can't sort the actual dictionary since they're mapping. You can,
>however, put the values in a list and sort the list. Something like
>this:
>
>    for key in thedict.keys():
>        sortedlist.append( (key, thedict[key]) )
>    sortedlist.sort()
>
>
>Test-run:
>
>>>> foo = {"foo":[1,2,3], "bar":[2,3,4], "gazonk":[3,4,5]}
>>>> foo
>{'foo': [1, 2, 3], 'gazonk': [3, 4, 5], 'bar': [2, 3, 4]}
>>>> sorted = []
>>>> for key in foo.keys():
>...   sorted.append( (foo[key], key) )
>... 
>>>> sorted.sort()
>>>> sorted
>[([1, 2, 3], 'foo'), ([2, 3, 4], 'bar'), ([3, 4, 5], 'gazonk')]
>
>
>
>-- 
>Rikard Bosnjakovic - http://a214.ryd.student.liu.se/cv/ - ICQ: 1158217
>
>Anyone sending unwanted advertising e-mail to my address will be
>charged $250 for network traffic and computing time. By extracting my
>address from this message or its header, you agree to these terms.




More information about the Python-list mailing list