Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort when values are None or empty strings python

I have a list with dictionaries in which I sort them on different values. I'm doing it with these lines of code:

def orderBy(self, col, dir, objlist):
    if dir == 'asc':
        sorted_objects = sorted(objlist, key=lambda k: k[col])
    else:
        sorted_objects = sorted(objlist, key=lambda k: k[col], reverse=True)
    return sorted_objects

Now the problem is that I occasionally have null values or empty strings when I try to sort and then it all breaks down.

I'm not sure but i think that this is the exception that's thrown: unorderable types: NoneType() < NoneType(). It occurs when there is None values on the column I'm trying to sort. For empty string values it works although they end up first in the list but I would like them to be last.

How can I solve this problem?

like image 224
Tryggast Avatar asked Dec 05 '22 03:12

Tryggast


1 Answers

If you want the None and '' values to appear last, you can have your key function return a tuple, so the list is sorted by the natural order of that tuple. The tuple has the form (is_none, is_empty, value); this way, the tuple for a None value will be (1, 0, None), for '' is (0, 1, '') and for anything else (0, 0, "anything else"). Thus, this will sort proper strings first, then empty strings, and finally None.

Example:

>>> list_with_none = [(1,"foo"), (2,"bar"), (3,""), (4,None), (5,"blub")]
>>> col = 1
>>> sorted(list_with_none, key=lambda k: (k[col] is None, k[col] == "", k[col])) 
[(2, 'bar'), (5, 'blub'), (1, 'foo'), (3, ''), (4, None)]
like image 61
tobias_k Avatar answered Dec 15 '22 01:12

tobias_k