TypeError:“<" 'dict'和'dict'实例之间不受支持 [英] TypeError: '<' not supported between instances of 'dict' and 'dict'
问题描述
我在python 2.7中具有按值排序的功能,但是我试图升级到python 3.6,却收到该错误:
I had a perfectly functioning sort by value in python 2.7 but I'm trying to upgrade to python 3.6 and I get that error:
TypeError:'<' 'dict'和'dict'实例之间不支持
TypeError: '<' not supported between instances of 'dict' and '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声明为列表时将其视为命令.如何按名称属性对其进行排序?
Why it's considered as a dict when I declare my server_list as a list. How can I make it sort by my name attribute?
推荐答案
Python 2的字典排序顺序为且了解甚少.只是因为Python 2试图使所有东西都可排序而起作用.
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.
对于您的特定情况,对于具有单个键的{'name': ...}
词典,排序由该单个键的值确定.
For your specific case, with {'name': ...}
dictionaries with a single key, the ordering was determined by the value for that single key.
在Python 3中,字典不再可排序(以及许多其他类型),只需使用该值作为排序键即可:
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)
这篇关于TypeError:“<" 'dict'和'dict'实例之间不受支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!