[Tutor] Sorting a dictionary

Pujo Aji ajikoe at gmail.com
Fri Nov 4 10:45:24 CET 2005


Hallo,
 you can also sort based on the values:

>>> list_of_nums = nums.items()
>>> list_of_nums.sort(lambda x,y: cmp(x[1],y[1]))
Cheers,
pujo


 On 11/4/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
>
> On Fri, 4 Nov 2005, Johan Geldenhuys wrote:
>
> > In my new project I needed a dictionary with TCP/UDP port numbers as
> > keys and the service for that key as the value. I got the info from the
> > services file in Linux and compiled a dictionary as I needed.
> >
> > The only thing that I want to do is to sort the dictionary from the
> > smallest key number to the largest key number.
>
> Hi Johan,
>
> Is this so you can more easily read the dictionary better? Be aware that
> dictionaries in Python are implemented as "hashtables", and these
> hashtables are deliberately "misordered" to make them work fast.
>
>
> We can take the items() of a dictionary, and sort those. For example:
>
> ######
> >>> nums = {'one' : 1, 'two' : 2, 'three' : 3 }
> >>> nums
> {'three': 3, 'two': 2, 'one': 1}
> >>> nums.items()
> [('three', 3), ('two', 2), ('one', 1)]
> ######
>
> We see that items() is a list of key-value pairs. We can sort lists by
> using their sort method().
>
> ######
> >>> list_of_nums = nums.items()
> >>> list_of_nums.sort()
> >>> list_of_nums
> [('one', 1), ('three', 3), ('two', 2)]
> ######
>
>
> Is this what you're looking for? If you have more questions, please feel
> free to ask.
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20051104/b0853bda/attachment.htm


More information about the Tutor mailing list