TypeError: '<' not supported between instances of 'dict' and 'dict'

六月ゝ 毕业季﹏ 提交于 2020-02-24 07:06:38

问题


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: '<' not supported between instances of 'dict' and 'dict'

Here is my code

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)

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?


回答1:


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)


来源:https://stackoverflow.com/questions/55695479/typeerror-not-supported-between-instances-of-dict-and-dict

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