python - python中字典的排序列表

标签 python list

我有这个列表:

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 传递给 sortsorted 以降序排序。

由于大写字母被认为小于对应的小写版本(由于它们的 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/

相关文章:

python - 尝试生成 5 个随机项目,有时会生成 4 个

python - Django - Celery 连接被拒绝

javascript - 当列表项的数量未知时,如何在加载每个列表项后立即对其进行一项一项修改

c# - 升序排列

python - 从字典列表中获取值列表?

python - Python 3.4 中的类对象数组

java - HashMap 一个键关联到一个列表

python - Apache mod_wsgi Django 设置 - 禁止您无权访问此服务器上的/mysite

python - 如何将 Keras Sequential CNN 的训练数据转换为正确的张量形状?

Python:如何让用户输入自己的解决方案到答案键