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.
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'}]
>>> 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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With