Sort list of dictionaries by key (case insensitive)

Nico Grubert nicogrubert at gmail.com
Wed Jan 13 16:18:23 CET 2010


Thanks a lot Stefan & Peter.

I'm almost there (except sorting of umlauts does not work yet).


import locale

def sorted(items, key):
     decorated = [(key(item), index, item) for index, item in
                   enumerate(items)]
     decorated.sort()
     return [item[2] for item in decorated]

items = [{'title':'the Ähnlich', 'id':1},
          {'title':'The Storm', 'id':2},
          {'title':'the bible','id':3},
          {'title':'The thunder', 'id':4}]

print sorted(items, key=lambda d: locale.strxfrm(d.get('title')))

-> [{'id': 2, 'title': 'The Storm'}, {'id': 4, 'title': 'The thunder'}, 
{'id': 3, 'title': 'the bible'}, {'id': 1, 'title': 'the \xc4hnlich'}]


The entry with the umlaut is the last item in but according to german 
umlaut rules it should be the first item in the result.
Do I have to set anything with the locale module?


Regards
Nico




More information about the Python-list mailing list