Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list with an exception in Python

I want to sort a dictionary alphabetically but we have other letters in Turkish because of that i can't use sorted() function.

For example we have letter "ç" which comes after letter "c". How can i make letter "ç" comes after letter "c"?

Btw it will not be just 1 letter we have plenty more and dictionary will contain hundereds of words and values.

like image 336
confusedProgrammer Avatar asked Dec 08 '25 01:12

confusedProgrammer


2 Answers

Here is a simple solution based on the Turkish alphabet:

alphabet = "abcçdefgğhıijklmnoöprsştuüvyz"
words = ["merhaba", "aşk", "köpek", "Teşekkürle"]

sorted_words = sorted(words, key=lambda word: tuple(alphabet.index(c) for c in word.lower()))

This code is able to sort words using the lexicographic order. It also works with words containing capital letters.

like image 56
Riccardo Bucco Avatar answered Dec 10 '25 15:12

Riccardo Bucco


You can use key argument for sorted, however the main challenge is how to define which letter is "bigger". Maybe you can use some table of letters' values to sort them. Like this:

LETTER_VALUES = {
    ...
    "c": 100,
    "ç": 110
    ...
    }

sorted_ar = sorted(char_array, key=lambda ch: LETTER_VALUES.get(ch1, ord(ch)))

Of course, numbers are just random for example and ord the simplest example for "failure default".

like image 32
Valentin Briukhanov Avatar answered Dec 10 '25 15:12

Valentin Briukhanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!