sorting list of dictionnaries in python -
i have list :
l = [{'status': 1, 'country': 'france'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}] how sort list country (or status) elements, asc/desc.
use list.sort() sort list in-place or sorted 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 optional key word argument reverse = true sort , sorted sort in descending order.
as upper-case alphabet considered smaller it's corresponding smaller-case version(due ascii value), may have use str.lower well.
>>> l.sort(key= lambda x:x['country'].lower()) >>> l [{'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'france'}, {'status': 1, 'country': 'usa'}]
Comments
Post a Comment