【发布时间】:2014-04-15 12:24:47
【问题描述】:
为什么 dicts 在 python2 中是可排序的,而在 python3 中是不可排序的?我在文档中的任何地方都找不到它。
Python 3.3.4 (default, Feb 11 2014, 16:14:21)
>>> sorted([{'a':'a'},{'b':'b'}])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() < dict()
对比
Python 2.7.6 (default, Feb 26 2014, 12:01:28)
>>> sorted([{'a':'a'},{'b':'b'}])
[{'a': 'a'}, {'b': 'b'}
【问题讨论】:
-
不,您希望它们按什么顺序排列?
-
嗯,我错了,key和value都用了;不过,由于字典本身是无序的,这实际上并没有多大意义。
-
有关 Python 2 功能的参考:Is there a description of how cmp works for dict objects in Python 2?
-
为什么在 Python 3 中被放弃了?它是否在某处的某些文档中找到?
-
但是甚至没有记录顺序,并且在所有用例中都没有意义。显式优于隐式;您需要对字典进行排序,您需要自己定义正确的顺序应该是什么。
标签: python sorting python-3.x dictionary python-2.x