Ahsan
Ahsan

Reputation: 11832

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..

Upvotes: 5

Views: 2563

Answers (3)

martineau
martineau

Reputation: 123501

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 )

Upvotes: 4

Winston Ewert
Winston Ewert

Reputation: 45059

members_list.sort( key = lambda member: getattr(member,sort_by).lower(), reverse = False )

Upvotes: 6

Exelian
Exelian

Reputation: 5888

It seems this question is about django. You might want to think about returning a sorted queryset instead. This means you can leave the sorting too the database and not bother with it your self. See this site: django

Upvotes: 1

Related Questions