[Tutor] Sorting a dictionary

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Nov 4 09:26:26 CET 2005



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.



More information about the Tutor mailing list