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.
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.
Here's a way:
return sorted(p, key=lambda x: x['first_name'].lower())
>>> 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'}]
>>>
It looks like you want sorted(p, key=lambda d: d['first_name'].lower())
.
>>> 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'}]
def sortProfiles(p):
return sorted(p, key=lambda el: el['first_name'].lower())
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.