python如何对字典列表进行排序? [英] How does python sort a list of dictionaries?

查看:905
本文介绍了python如何对字典列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用sorted内置函数而不提供任何可选参数,python如何对字典列表进行排序?

Using the sorted built-in function without providing any optional arguments, how does python sort a list of dictionaries?

推荐答案

Python 2确实尝试提供基于长度的排序(对于 all 类型,它这样做)(首先是短义) ,如果长度相等,则按键(较小的键排在前),然后,如果所有键相等,则按值(较小的值排在前);请参见 characterizedict_compare函数 dictobject.c源代码.

Python 2 does attempt to provide an ordering (it does so for all types), first based on length (shorted dicts first), if the lengths are equal then by keys (a smaller key goes first), then if all keys are equal then on values (smaller values go first); see the characterize and dict_compare functions in the dictobject.c source code.

简短演示:

>>> sorted([{1:2}, {}])
[{}, {1: 2}]
>>> sorted([{1:2}, {0:1}])
[{0: 1}, {1: 2}]
>>> sorted([{1:2}, {1:1}])
[{1: 1}, {1: 2}]

在Python 3中,它根本不对它们进行排序;排序命令确实没有任何意义:

In Python 3, it doesn't sort them at all; sorting dicts really makes no sense:

>>> sorted([{}, {}])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() < dict()

请参阅新增功能"中的订购比较部分. Python 3文档.

See the Ordering Comparisons section of the What's New in Python 3 document.

这篇关于python如何对字典列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆