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..
members_list.sort( key = lambda member: getattr(member,sort_by).lower(), reverse = False )
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With