Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list sorting case insensitive using operator.attrgetter

hi i have list of dictionaries .. and i want to sort it case insensitive

members = Person.objects.filter(person=person_id)
members_list = list(members)

members_list.sort( key = operator.attrgetter( sort_by ), reverse = False )

here sort_by have attribute name by whom i want to sort. Now how can i sort with case insensitive ??

Please help..

like image 797
Ahsan Avatar asked Jan 21 '11 14:01

Ahsan


2 Answers

members_list.sort( key = lambda member: getattr(member,sort_by).lower(), reverse = False )
like image 172
Winston Ewert Avatar answered Sep 28 '22 12:09

Winston Ewert


If sort_by is a variable containing a string with the name of the attribute you want to use for sorting and you want to use operator.attrgetter(), you could use this which converts the value of the attribute it fetches to all lowercase characters for comparisons during the sort:

members_list.sort( key = lambda mbr: operator.attrgetter( sort_by )( mbr ).lower(),
                   reverse = False )

Although something like the following is easier to read as well as more efficient:

get_key = operator.attrgetter( sort_by )
members_list.sort( key = lambda mbr: get_key( mbr ).lower(), reverse = False )
like image 40
martineau Avatar answered Sep 28 '22 10:09

martineau