Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 678
XChoopa Avatar asked Apr 15 '19 18:04

XChoopa


1 Answers

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)
like image 140
Martijn Pieters Avatar answered Sep 17 '22 08:09

Martijn Pieters