我有这个列表:
L = [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}]
如何按 country
(或按 status
)元素 ASC/DESC 对列表进行排序。
最佳答案
使用 list.sort()
对列表进行就地排序或使用 sorted
获取新列表:
>>> 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'}]
您可以将可选的关键字参数 reverse = True
传递给 sort
和 sorted
以降序排序。
由于大写字母被认为小于对应的小写版本(由于它们的 ASCII 值),因此您可能还必须使用 str.lower
。
>>> L.sort(key= lambda x:x['country'].lower())
>>> L
[{'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'France'}, {'status': 1, 'country': 'usa'}]
关于python - python中字典的排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16539917/