Sort list of dictionaries by key (case insensitive)

N

Nico Grubert

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
 
P

Peter Otten

Nico said:
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
 
F

Florian Diesch

Nico Grubert said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,744
Latest member
CortneyMcK

Latest Threads

Top