views:

97

answers:

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

+2  A: 

Here's a way:

return sorted(p, key=lambda x: x['first_name'].lower())
Justin Peel
+3  A: 
>>> 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'}]
>>>
John Machin
+1  A: 

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

Mike Graham
A: 
>>> 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'}]
voyager
This overcomplicates the solution. Also, `my_itemgetter` should be named better.
Mike Graham
care to fix your indentation?
John Machin
@Mike: he should not be copying any kind of snippet from any site. This is intended for him to understand what is needed, while providing a generic solution. He can name it whatever he wants. By not using lambda he can then make the `itemgetter` as complex (custom?) as he wants.
voyager
@voyager, Code snippets we offer to educate people should be good in every way, though I admit the remark about the name was quite pedantic. In any event, this seemed slightly more complicated than necessary for a solution using either `lambda` or `def`. It also lets errors pass silently.
Mike Graham
+1  A: 
def sortProfiles(p):
    return sorted(p, key=lambda el: el['first_name'].lower())
Kamil Szot
A: 

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.

Alex Martelli
Do you dislike lambda?
TIMEX
@alex, yep, I do dislike it, though I do use it sometimes for particularly simple cases. `def` is superior for profiling, debugging, ease of insertion of `logging` calls, clarity of tracebacks, and generality (allows the use of statements, not just expressions) -- `lambda` has no compensating concrete advantages, just saves you from having to think of a name;-).
Alex Martelli