Sort dictionary data

Lemniscate d_blade8 at hotmail.com
Mon May 20 18:54:24 EDT 2002


1) It doesn't work.

2) It shouldn't work.  Dictionaries are unordered, by definition. 
What you end up with is trying to sort an unordered list.  It may
sort, but the dictionary immediately unsorts itself.  Also, since sort
returns None, you can't even see the sorted version.

Example:
>>> myDict = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g', 0:'za'}
>>> myDict.values()
['za', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> myDict.values().sort()   # Nothing gets returned
>>> myDict.values()
['za', 'a', 'b', 'c', 'd', 'e', 'f', 'g']



What you may want to do is something like:
>>> DicValList = myDict.values()
>>> DicValList
['za', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> DicValList.sort()
>>> DicValList
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'za']
>>> 

This way you can loop over them (you can get the illusion of sorting a
dictionary by key by doing this with a list from myDict.keys(),
sorting the list and then going through each one with a call to the
values.  Anyways, have fun.

Dialtone <dialtone#/N0SPAM/#@aruba.it> wrote in message news:<sjhieuovp2813u2ca4hu9d6l909uuj3fc7 at 4ax.com>...
> On Mon, 20 May 2002 15:10:32 -0300, Marcus Laranjeira
> <m.laranjeira at datacraft.com.br> wrote:
> 
> >does anyone knows how can this be done ? Is there any ready module to do
> >such sorting ?
> 
> Did you try with dic.values().sort()?
> 
> I have not tried but it should work as you want.



More information about the Python-list mailing list