dicts are not orderable in python 3?

放肆的年华 提交于 2019-11-30 20:59:54
Martijn Pieters

Python 2 uses an undocumented ordering, implemented as a .__cmp__() special method.

The ordering only makes sense in a limited set of use-cases, and only exists because Python 2 tries to make everything orderable.

Python 3 drastically cleaned up Python's ordering story; .__cmp__() is gone, and only types that actually have a natural ordering (such as numbers and strings) now support ordering. For everything else, you'll need to explicitly define an ordering.

Dictionaries do not have a natural ordering. If you do need to order dictionaries, you need to define an explicit order that makes sense for your use case. If that means comparing just the keys, do so (e.g. use key=sorted), etc.

mhlester

You'll need to sort with a key (documentation). Only you know what key you want, but here's one example:

>>> dicts = [{'a':'a'},{'b':'b'}]
>>> sorted(dicts, key=lambda x:sorted(x.keys()))
[{'a': 'a'}, {'b': 'b'}]

This is sorting by keys, where the dict with the "lowest" key comes first


Edit: as pointed out by Martijn Pieters, this answer describes exactly how Python 2 does it. But you should sort in the way that makes sense to your situation, which may be fundamentally different from how Python 2 does it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!