3

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • You can provide a key function that maps letters to e.g. an ordinal position in the alphabet. – jonrsharpe Dec 28 '19 at 17:36
  • So do you have al alphabet? That is a list of all the letters you need? – Riccardo Bucco Dec 28 '19 at 17:37
  • Related: [Does Python 3 string ordering depend on locale?](https://stackoverflow.com/q/26505661/4518341), [How do I sort unicode strings alphabetically in Python?](https://stackoverflow.com/q/1097908/4518341), [Python not sorting unicode properly. Strcoll doesn't help](https://stackoverflow.com/q/3412933/4518341). Also related to Turkey and internationalization: [What is The Turkey Test?](https://stackoverflow.com/q/796986/4518341) – wjandrea Dec 28 '19 at 19:35

3 Answers3

4

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.

Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
1

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".

Valentin Briukhanov
  • 1,263
  • 9
  • 13
0

You can achieve this by injecting your own alphabet order, example:

letters = "abcçdefgğhıijklmnoöprsştuüvyz"
letters_dict = {i:letters.index(i) for i in letters}
print(sorted("açobzöğge", key=letters_dict.get))

The above should output: ['a', 'b', 'ç', 'e', 'g', 'ğ', 'o', 'ö', 'z']

Tomer Gal
  • 933
  • 12
  • 21