TIMEX
TIMEX

Reputation: 272174

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.

Upvotes: 2

Views: 4302

Answers (6)

Esteban Küber
Esteban Küber

Reputation: 36852

>>> def my_itemgetter(attr):
        def get_attr(obj):
            return obj.get(attr, "").lower()
        return get_attr

>>> a= [{"a":"dA"},{"a":"ab"},{"a":"Ac"},{"a":"aa"}]
>>> sorted(a, key=my_itemgetter("a"))
[{'a': 'aa'}, {'a': 'ab'}, {'a': 'Ac'}, {'a': 'dA'}]

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 882341

If you dislike lambda, you can use a named function as your key-extractor, e.g:

def sortProfiles(p):
    def lowerName(d):
        return d['first_name'].lower()
    return sorted(p, key=lowerName)

The def statement can appear just about anywhere another statement could, including in another function's body. In this case, the choice among a nested def, a lambda, or a separate def outside of sortProfiles, is mostly a matter of style, though the last of these could offer some performance gain.

Upvotes: 1

Kamil Szot
Kamil Szot

Reputation: 17817

def sortProfiles(p):
    return sorted(p, key=lambda el: el['first_name'].lower())

Upvotes: 1

Mike Graham
Mike Graham

Reputation: 76753

It looks like you want sorted(p, key=lambda d: d['first_name'].lower()).

Upvotes: 1

John Machin
John Machin

Reputation: 83002

>>> 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'}]
>>>

Upvotes: 10

Justin Peel
Justin Peel

Reputation: 47082

Here's a way:

return sorted(p, key=lambda x: x['first_name'].lower())

Upvotes: 2

Related Questions