2

I have a list of dictionaries with some strings containing artists and their albums (fetched from Spotify). I want to sort this dictionary by artist first and then by album. But I want to use a locale aware sort (German in my case).

I found out that I can sort a list of dictionaries with multiple key like so:

somelist.sort(key=lambda k: (k['artist'].lower(), k["album"].lower()))

.lower because I want a case insensitive sort.

This works fine for English named artists and albums, but not for none-English. I found also out that for locale aware sorts I can use somelist.sort(key=locale.strxfrm).

What I don't understand: How can I combine locale-aware AND multiple key sorts?

1 Answer 1

2

Why not compose the two?

def normalizeSortString(s):
    return local.strxfrm(s).lower()

def getSortKey(k):
    return (normalizeSortString(k['artist']), normalizeSortString(k["album"]))

somelist.sort(key=getSortKey)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.