[Tutor] Fw: utf locale sorting

Rich Lovely roadierich at googlemail.com
Wed Sep 16 16:58:07 CEST 2009


2009/9/16 Igor Mavrović - Maqui at IRB <igor.mavrovic at irb.hr>:
> Hi,
>
> I know about the use of locale module:
>
>>>> import locale
>>>> locale.setlocale(locale.LC_ALL, "hr_HR.UTF8")
>>>> print sorted(words, key=locale.strxfrm)
>
> but I have specific and complicated data structure (list of lists containing
> strings, tuples and dictionaries) due to LDAP search result data.
> So I use the 'key' option to get to the neaded attributes, and can't use it
> for the locale setting. How can I sort this monster list by attribute values
> inside it, and still get the correct sorting order?
>
> Anyone? Thanks in advance!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

The key argument of sorted() and the like takes a function object, so
you could do something like the following:

def keyfunc(value):
   keyVal = value[0] #Or whatever lookups are needed
   return locale.strxfrm(keyVal)

then you can call sorted with:

print sorted(words, key=keyfunc)


You could also do the same with a lambda:

print sorted(words, key=lambda o: locale.strxfrm(o[0]))

Hope that helps
-- 
Rich "Roadie Rich" Lovely

There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.


More information about the Tutor mailing list