问题
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