Reputation: 1695
I have this list:
L = [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}]
How to sort this list by country
(or by status
) elements, ASC/DESC.
Upvotes: 2
Views: 196
Reputation: 304493
Pulling the key out to a named function is a good idea for real code, because now you can write tests for it explicitly
def by_country(x):
# For case insensitive ordering by country
return x['country'].lower()
L.sort(key=by_country)
Of course you can adapt to use sorted(L, key=...)
or reverse=True
etc.
Upvotes: 2
Reputation: 251196
Use list.sort()
to sort the list in-place or sorted
to get a new list:
>>> L = [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}]
>>> L.sort(key= lambda x:x['country'])
>>> L
[{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}]
You can pass an optional key word argument reverse = True
to sort
and sorted
to sort in descending order.
As a upper-case alphabet is considered smaller than it's corresponding smaller-case version(due to their ASCII value), so you may have to use str.lower
as well.
>>> L.sort(key= lambda x:x['country'].lower())
>>> L
[{'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'France'}, {'status': 1, 'country': 'usa'}]
Upvotes: 9
Reputation: 133764
>>> from operator import itemgetter
>>> L = [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}]
>>> sorted(L, key=itemgetter('country'))
[{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}]
>>> sorted(L, key=itemgetter('country'), reverse=True)
[{'status': 1, 'country': 'usa'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'France'}]
>>> sorted(L, key=itemgetter('status'))
[{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}]
Upvotes: 7