[Tutor] Dictionary

alan.gauld@bt.com alan.gauld@bt.com
Fri Nov 22 06:53:12 2002


>       Im trying to sort a dictionary by keys or values and I 
> would like to know if have a way to do this.

You can extract the keys and sort them then use the sorted list to access
the values:

d = {1:2,3:4,5:6}

keys = d.keys().sort()

for key in keys: print d[key]

You can do the same with the values but of course getting 
the keys which match the values is more tricky!

HTH,

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld