在Python 2中,您可以将字典与小于和大于运算符进行比较,这意味着它们可以进行排序/排序:
>>> {'a': 2} < {'a': 3}
True
>>> {'a': 7} < {'a': 3}
False
>>> {'b': 4} > {'c': 1}
False
>>> sorted([{'c': 1}, {'a': 5}, {'b':2 }])
[{'a': 5}, {'b': 2}, {'c': 1}]
在Python 3中,您不能这样做:
>>> {'a': 2} < {'a': 3}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'
>>> sorted([{'c': 1}, {'a': 5}, {'b':2 }])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'
<
运算符是如何定义的?)