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'}]
str.lower here as dictionary wise canada must come before France.str.lowerPulling 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.
collections.namedtupleinstead. It will make a lot of your code, including sorting, much simpler to read and write. See this link for details