【问题标题】:TypeError: '<' not supported between instances of 'dict' and 'dict'TypeError:'dict'和'dict'的实例之间不支持'<'
【发布时间】:2019-09-05 19:22:31
【问题描述】:

我在 python 2.7 中有一个完美的按值排序,但我正在尝试升级到 python 3.6,但我收到了这个错误:

TypeError: '

这是我的代码

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)

为什么当我将 server_list 声明为列表时它被视为字典。如何让它按我的 name 属性排序?

【问题讨论】:

标签: python-3.x sorting


【解决方案1】:

Python 2 的字典排序顺序是 quite involved,但人们很难理解。它只是碰巧起作用了,因为 Python 2 试图让所有东西都可以订购。

对于您的具体情况,{'name': ...} 字典具有单个键,排序由该单个键的值确定。

在 Python 3 中,字典不再可排序(与许多其他类型一起),只需使用该值作为排序键:

server_list.sort(key=lambda x: x[0]['name'], reverse=False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2020-09-07
    相关资源
    最近更新 更多