Sort list of tuples considering locale (swedish ordering) Sort list of tuples considering locale (swedish ordering) postgresql postgresql

Sort list of tuples considering locale (swedish ordering)


When running LC_ALL=sv_SE.UTF-8 sort on your example on Ubuntu-10.04, it comes out with Wa before Vb (the "old way"), so Ubuntu does not seem to agree with the "new way".Since PostgreSQL relies on the operating system for this, it will behave just the same as the OS given the same lc_collate.

There is actually a patch in debian glibc related to this particular sort issue:http://sourceware.org/bugzilla/show_bug.cgi?id=9724But it was objected to and not accepted. If you only need this behavior on a system you administer, you can still apply the change of the patch to /usr/share/i18n/locales/sv_SE and rebuild the se_SV locale by running locale-gen sv_SE.UTF-8. Or better yet, create your own alternative locale derived from it to avoid messing with the original.


This solution is complex because key=locale.strxfrm works fine with single lists and dictionaries, but not with lists of lists orlists of tuples.

Changes from Py2 -> Py3 : use locale.setlocale(locale.LC_ALL, '')and key='locale.strxfrm' (instead of 'cmp=locale.strcoll').

list_of_tuples = [('Wa', 1), ('Vb',2), ('Wc',3), ('Vd',4), ('Öa',5), ('äa',6), ('Åa',7)]def locTupSorter(uLot):    "Locale-wise list of tuples sorter - works with most European languages"    import locale    locale.setlocale(locale.LC_ALL, '') # get current locale    dicTups = dict(uLot)          # list of tups to unsorted dictionary    ssList = sorted(dicTups, key=locale.strxfrm)    sLot = []    for i in range(len(ssList)):  # builds a sorted list of tups         tfLot = ()        elem = ssList[i]          # creates tuples for list        tfLot = (elem, dicTups[elem])        sLot.append(tfLot)        # creates sorted list of tuples    return(sLot)print("list_of_tuples=\n", list_of_tuples)sortedLot = locTupSorter(list_of_tuples)print("sorted list of tuples=\n",sortedLot)