TypeError:“ dict”和“ dict”的实例之间不支持“ <”

Dom*_*Dom 1 sorting python-3.x

我在python 2.7中具有按值排序的功能,但是我试图升级到python 3.6,却收到该错误:

TypeError:“ dict”和“ dict”的实例之间不支持“ <”

这是我的代码

server_list = []

for server in res["aggregations"]["hostname"]["buckets"]:
    temp_obj = []
    temp_obj.append({"name":server.key})        
    temp_obj.append({"stat": server["last_log"]["hits"]["hits"][0]["_source"][system].stat})
    server_list.append(temp_obj)
    server_list.sort(key=lambda x: x[0], reverse=False)
Run Code Online (Sandbox Code Playgroud)

当我将server_list声明为列表时,为什么将其视为字典。如何按名称属性对其进行排序?

Mar*_*ers 5

Python 2's dictionary sort order was quite involved and poorly understood. It only happened to work because Python 2 tried to make everything orderable.

For your specific case, with {'name': ...} dictionaries with a single key, the ordering was determined by the value for that single key.

In Python 3, where dictionaries are no longer orderable (together with many other types), just use that value as the sorting key:

server_list.sort(key=lambda x: x[0]['name'], reverse=False)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢您的解释和解决方案。我只是一个试图在Python世界中生存的旧回收dba :) (2认同)