Sorting Objects by property using locale

thebjorn BjornSteinarFjeldPettersen at gmail.com
Fri Dec 21 09:37:33 EST 2007


Donn Ingle wrote:
> Hi,
>  Well, I'm beat. I can't wrap my head around this stuff.
>
> I need to create a list that will contain objects sorted by a "name"
> property that is in the alphabetical order of the user's locale.
>
> I used to have a simple list that I got from os.listdir and I could do this:
> l = os.listdir(".")
> l.sort(locale.strcoll)
> Which would work fine.
>
> But now I need to make objects (of different stripes) for each of the
> filenames returned and then I want to collect them all into a main list and
> have *that* main list be sorted.
>
> I started some test code like this: I hope the odd characters show.
>
> # -*- coding: utf8 -*-
>
> class Test(object):
>     def __init__(self,nam):
>         self.name = nam
>     def __cmp__(self, other):
>         return cmp(self.name, other.name)
>
> l = [ Test("ABILENE.ttf"), Test("Årgate.ttf"), Test("årse.ttf"),
> Test("Ärt.ttf"), Test("MomentGothic.ttf"), Test("öggi.ttf"),
> Test("Öhmygawd.ttf")]
>
> import locale
>
> l.sort() # won't work -> locale.strcoll)
>
> for i in l: print i.name
>
>
> Can anyone give me a leg-up?
>
> \d

You need to use the key argument to the sort function as well as the
cmp argument:

import os, locale

locale.setlocale(locale.LC_ALL, 'NO')

class Test(object):
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return self.name

fnames =  [Test(fname) for fname in os.listdir('.')]
fnames.sort(cmp=locale.strcoll, key=lambda t:t.name)

for fname in fnames:
    print fname

and the output was

abel.txt
aegis.txt
onsdag.txt
pysortdir.py
pysortdir.py~
ærlig.txt
ønske.txt
åbel.txt
aaron.txt
åte.txt

Which is even more correct than I hoped for -- in Norwegian, aa is
pronounced the same as å (which is the 29th letter in the Norwegian
alphabet) and is sorted according to pronunciation.

-- bjorn



More information about the Python-list mailing list