[Tutor] Sort dictionaries

Gonçalo Rodrigues op73418 at mail.telepac.pt
Mon Nov 15 22:52:17 CET 2004


David Holland wrote:

> Is there a built command to sort a dictionary keys or
> values by their length or do I have to write a
> function to do it myself ?
> 
> David

Dictionaries have no inherent concept of order so you cannot sort them. 
If you have a collection of objects, sorting them means that you put 
your objects in 1-1 correspondence with {0,...,n} where n is the number 
of objects in the collection: in Python terms, you need a list.

So suppose you have a dictionary:
 >>> dct = {(1, 2 , 3) : "ahab",
... (0,) : [],
... ("a", "test") : 3}
 >>> dct
{(0,): [], ('a', 'test'): 3, (1, 2, 3): 'ahab'}

And you want to sort your keys by length: One way to do this, is to 
first extract a list of keys and then you "decorate" them with theior 
length,

 >>> pairs = []
 >>> for key in dct.keys():
... 	pairs.append((len(key), key))
... 	
 >>> pairs
[(1, (0,)), (2, ('a', 'test')), (3, (1, 2, 3))]

Here we just extracted the keys via the dictionary keys method that 
returns a list and formed a list of 2-tuples where the *first* item 
(your sort criteria) is the length of the key and the second item is the 
key itself.

Now that we have a list, we just sort it:

 >>> pairs.sort()
 >>> pairs
[(1, (0,)), (2, ('a', 'test')), (3, (1, 2, 3))]
 >>>

This works because there is a natural order on tuples: the lexicographic 
order. First you compare the first item, if they are equal you compare 
the second item, etc.

I hope you can see how this procedure (btw it is called the 
decorate-sort-undecorate, or DSU for short, pattern) can be applied to 
your specific setting.

With my best regards,
G. Rodrigues

P.S: There is an hidden assumption in the code above: the keys must be 
comparable. If they are not, you have to write your own compare function.


More information about the Tutor mailing list