为什么我不能在Python 3.x中对字典列表进行排序?为什么我得到“TypeError:在“dict”和“dict'"示例之间不支持”〈“”?

brqmpdu1  于 2023-02-01  发布在  Python
关注(0)|答案(1)|浏览(152)

我在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)

为什么当我把server_list声明为一个列表时它被认为是一个dict。我怎样才能让它按我的name属性排序?

velaa5lx

velaa5lx1#

Python 2的字典排序顺序是quite involved,人们对此理解不多,它之所以能够工作,是因为Python 2试图让所有东西都是可排序的。
对于您的特定情况,如果{'name': ...}字典只有一个键,则排序由该键的值决定。
在Python 3中,字典不再是可排序的(还有许多其他类型),只需使用该值作为排序键:

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

相关问题