sorting strings numerically while dealing with missing values

Peter Otten __peter__ at
Wed Dec 28 15:39:20 EST 2016

Larry Martell wrote:

> I have a list containing a list of strings that I want to sort
> numerically by one of the fields. I am doing this:
> sorted(rows, key=float(itemgetter(sortby)))
> Which works fine as long as all the sort keys convert to a float.

No, that cannot work; unless you have redefined float() you 'l get a 
TypeError either here

>>> from operator import itemgetter
>>> float(itemgetter(42))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: float() argument must be a string or a number, not 

or here:

>>> sorted("abc", key=3.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable

> Problem is that some are blank or None and those throw an exception.
> How can I handle that case and still sort? I'd want the blank or None
> fields to come out either at the beginning or end of the sorted list
> (not sure what the customer wants for this yet).

Make the key function return a tuple:

>>> def none_blank_float(value):
...     if value is None: return (0,)
...     if not value: return (1,)
...     return 2, float(value)
>>> sorted(["1", "10", "2", None, "3", "", "5"], key=none_blank_float)
[None, '', '1', '2', '3', '5', '10']

More information about the Python-list mailing list