Sort list of dictionaries by key (case insensitive)

Peter Otten __peter__ at web.de
Wed Jan 13 06:05:04 EST 2010


Nico Grubert wrote:

> I have the following list 'mylist' that contains some dictionaries:
> 
> mylist = [{'title':'the Fog', 'id':1},
>            {'title':'The Storm', 'id':2},
>            {'title':'the bible', 'id':3},
>            {'title':'The thunder', 'id':4}
>           ]
> 
> How I can sort (case insensitive) the list by the dictioary's 'title' key?
> 
> The result should be this list:
> [{'title':'the bible', 'id':3},
>   {'title':'the Fog', 'id':1},
>   {'title':'The Storm', 'id':2},
>   {'title':'The thunder', 'id':4}
> ]
> 
> I am using Python 2.4.

Python 2.4.6 (#2, Mar 19 2009, 10:02:47)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
'de_DE.UTF-8'
>>> mylist = [{'title':'the Fog', 'id':1},
...            {'title':'The Storm', 'id':2},
...            {'title':'the bible', 'id':3},
...            {'title':'The thunder', 'id':4}
...           ]
>>> mylist.sort(key=lambda item: locale.strxfrm(item["title"]))
>>> import pprint
>>> pprint.pprint(mylist)
[{'id': 3, 'title': 'the bible'},
 {'id': 1, 'title': 'the Fog'},
 {'id': 2, 'title': 'The Storm'},
 {'id': 4, 'title': 'The thunder'}]

Peter



More information about the Python-list mailing list