[Tutor] Fw: utf locale sorting

Igor Mavrović - Maqui@IRB igor.mavrovic at irb.hr
Wed Sep 16 17:45:15 CEST 2009


Sorry Kent, I should have put it in the original message...
This is the way I call the sorted function:

    # resultSet looks like: [[("DN", {"":["", ...], ...})], ...]

    resultSetSortedByCn = sorted(resultSet, key=lambda x:(x[0][1]["sn"], 
x[0][1]["givenName"]))
    resultSetSortedByOu = sorted(resultSet, key=lambda x:(x[0][1]["ou"], 
x[0][1]["sn"], x[0][1]["givenName"]))

I have to use it like this for obvious reasons (sort by org-unit, surname 
and then name). Therefore Rich's suggestion:

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

can't work 'cause strxfrm's argument must be a string, not a tuple...

What do you think?

Igor


----- Original Message ----- 
From: Rich Lovely
To: Igor Mavrović - Maqui at IRB
Cc: tutor at python.org
Sent: Wednesday, September 16, 2009 4:58 PM
Subject: Re: [Tutor] Fw: utf locale sorting


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.


----- Original Message ----- 
From: Kent Johnson
To: Igor Mavrović - Maqui at IRB
Cc: tutor at python.org
Sent: Wednesday, September 16, 2009 4:33 PM
Subject: Re: [Tutor] Fw: utf locale sorting


On Wed, Sep 16, 2009 at 9:51 AM, Igor Mavrović - Maqui at IRB
<igor.mavrovic at irb.hr> wrote:
> 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?

The key= parameter can be any function. What are you using now? Just
add the call to locale.strxfrm() to your key function. If you are
currently using operator.itemgetter or operator.attrgetter you will
have to change to explicit attribute access.

Kent 



More information about the Tutor mailing list