[Tutor] Dictionary

Bob Gailer ramrom@earthling.net
Thu Nov 21 18:17:02 2002


At 09:08 PM 11/21/2002 -0200, lobow@brturbo.com wrote:
>  Im trying to sort a dictionary by keys or values and I would like to 
> know if have a way to do this.

There are several ways to approach this, depending on what you really want. 
First note that a dictionary can't be sorted. So the results would best go 
in a list.

Make the dictionary:
 >>> d = {}
 >>> d['a']=3
 >>> d['b']=2
 >>> d['c']=1
 >>> d
{'a': 3, 'c': 1, 'b': 2}

Make a list of key,value pairs:
 >>> l = d.items()
 >>> l
[('a', 3), ('c', 1), ('b', 2)]

Sort the list on keys:
 >>> l.sort()
 >>> l
[('a', 3), ('b', 2), ('c', 1)]

For a value sort, construct the list of value, key pairs:
 >>> r = [(key, val) for val, key in d.items()]
 >>> r.sort()
 >>> r
[(1, 'c'), (2, 'b'), (3, 'a')]

HTH

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625