Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make this sorting case insensitive?

def sortProfiles(p):
    return sorted(p, key=itemgetter('first_name'))

I have a list with dictionaries. This function allows me to sort them by their first_name. However, it's case-sensitive.

like image 275
TIMEX Avatar asked Jul 11 '26 21:07

TIMEX


2 Answers

>>> from operator import itemgetter
>>> p = [{'fn':'bill'}, {'fn':'Bob'}, {'fn':'bobby'}]
>>> sorted(p, key=itemgetter('fn'))
[{'fn': 'Bob'}, {'fn': 'bill'}, {'fn': 'bobby'}]
>>> sorted(p, key=lambda x: x['fn'].lower())
[{'fn': 'bill'}, {'fn': 'Bob'}, {'fn': 'bobby'}]
>>>
like image 128
John Machin Avatar answered Jul 14 '26 10:07

John Machin


Here's a way:

return sorted(p, key=lambda x: x['first_name'].lower())
like image 33
Justin Peel Avatar answered Jul 14 '26 11:07

Justin Peel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!