Sort when values are None or empty strings python

2024/10/12 17:19:36

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?

Answer

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)]
https://en.xdnf.cn/q/69629.html

Related Q&A

How to tell if you have multiple Djangos installed

In the process of trying to install django, I had a series of failures. I followed many different tutorials online and ended up trying to install it several times. I think I may have installed it twice…

Python Numerical Integration for Volume of Region

For a program, I need an algorithm to very quickly compute the volume of a solid. This shape is specified by a function that, given a point P(x,y,z), returns 1 if P is a point of the solid and 0 if P i…

invalid literal for int() with base 10: on Python-Django

i am learning django from official django tutorial. and i am getting this error when vote something from form. this caused from - probably - vote function under views.py here is my views.py / vote func…

How to use HTTP method DELETE on Google App Engine?

I can use this verb in the Python Windows SDK. But not in production. Why? What am I doing wrong?The error message includes (only seen via firebug or fiddler)Malformed requestor something like thatMy…

Python heapq : How do I sort the heap using nth element of the list of lists?

So I have lists of lists getting added to the heap; eg:n = [[1, 5, 93],[2, 6, 44],[4, 7, 45],[6, 3, 12]]heapq.heapify(n)print(n)This compares and sorts according to the lists first element.My question …

How strings are stored in python memory model

I am from c background and a beginner in python. I want to know how strings are actually stored in memory in case of python.I did something likes="foo"id(s)=140542718184424id(s[0])= 140542719…

The _imaging C module is not installed (on windows)

Im trying to generate some pdf with django/PIL/Imaging and everything is good until I attempt to put some images into the pdf:Exception Type: ImportError Exception Value: The _imaging C module is n…

HOW TO use fabric use with dtach,screen,is there some example

i have googled a lot,and in fabric faq also said use screen dtach with it ,but didnt find how to implement it? bellow is my wrong code,the sh will not execute as excepted it is a nohup taskdef dispatc…

Developing for the HDMI port on Linux

How would it be possible to exclusively drive the HDMI output from an application, without allowing the OS to automatically configure it for display output?For example, using the standard DVI/VGA as t…

Hive client for Python 3.x

is it possible to connect to hadoop and run hive queries using Python 3.x? I am using Python 3.4.1.I found out that it can be done as written here: https://cwiki.apache.org/confluence/display/Hive/Hiv…