Excalibur
Excalibur

Reputation: 316

Sort list of list with key and locale (here: german umlauts)

I know how to customize sort with the (simple) key=function. But how to do that, if I need a more complex key= function. I have problems in getting it together.

Here's the snippet: In the first example I use key=locale.strxfrm, which is good enough for this purpose. The second example I use another key= function (itemgetter). But I need both together.

import locale
import operator

locale.setlocale(locale.LC_ALL, "")
# on my computer: German_Germany.1252

lastnames = ["Bange", "Änger", "Amman", "Änger", "Zelch", "Ösbach"]
print(sorted(lastnames, key=locale.strxfrm)) # sorted correct
                                             # alphabetically for Germany
print()

lastnames_firstnames_groups =[
    ["Bange", "Michael", 2],
    ["Änger", "Ämma", 2],
    ["Amman", "Anton", 1],
    ["Änger", "Chris", 2],
    ["Zelch", "Sven", 1],
    ["Ösbach", "Carl", 1]
]
print(sorted(lastnames_firstnames_groups, key=operator.itemgetter(2,0,1)))
# The result is sorted as I expected (the german umlaute are NOT sorted
# the correct way). Is there a way to "add" the string tranformation strxfrm
# as in the first example to this. 

Any hints?

Upvotes: 2

Views: 1934

Answers (2)

jean-loup
jean-loup

Reputation: 609

Use strxfrm on the contatened, converted and ordered keys:

f = operator.itemgetter(2,0,1)
print(sorted(lastnames_firstnames_groups, key=lambda x: locale.strxfrm(' '.join(str(y) for y in f(x)))))

Upvotes: 0

Mike Graham
Mike Graham

Reputation: 76753

It sounds like you might want

print(
    sorted(
        lastnames_firstnames_groups,
        key=lambda t: (t[2], strxfrm(t[0]), strxfrm(t[1]))
    )
)

Upvotes: 3

Related Questions