Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Sort list of dictionaries by key (case insensitive) (http://www.velocityreviews.com/forums/t711639-sort-list-of-dictionaries-by-key-case-insensitive.html)

Nico Grubert 01-13-2010 07:45 AM

Sort list of dictionaries by key (case insensitive)
 
Hi there

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.


Regards,
Nico

Peter Otten 01-13-2010 11:05 AM

Re: Sort list of dictionaries by key (case insensitive)
 
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

Florian Diesch 01-13-2010 11:11 AM

Re: Sort list of dictionaries by key (case insensitive)
 
Nico Grubert <nicogrubert@gmail.com> writes:

> Hi there
>
> 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?


mylist.sort(key=lambda x: x['title'].lower())



Florian
--
<http://www.florian-diesch.de/software/easygconf/>


All times are GMT. The time now is 11:50 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.