Duncan Booth duncan.booth at invalid.invalid
Fri Jan 22 09:39:52 CET 2010

Wilbert Berendsen <wbsoft at> wrote:

> # sort the keys, longest first, so 'aa' gets matched before 'a', because
> # in Python regexps the first match (going from left to right) in a
> # |-separated group is taken
> keys = sorted(mapping.keys(), key=len, reverse=True)

This would do just as well (although see Iain King's response for the 
correct answer):

keys = sorted(mapping, reverse=True)

You don't need to specify key=len because the default sorting for two 
strings where one is a prefix of the other will always sort them that way 
anyway, and you don't need to call mapping.keys() because that's what 
sorted will sort anyway.

Duncan Booth

More information about the Python-list mailing list