Python sorting by attributes that can be None
<p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p>

<pre><code>sorted(items, key=attrgetter('data.value'))
</code></pre>

<p>And that'd work just fine. However, <code>data</code> can actually be <code>None</code> so obviously I couldn't access <code>value</code>.</p>

<p>How do you usually deal with scenarios like this?</p>

<p>PS: neither <a href="http://stackoverflow.com/questions/12971631/sorting-list-by-an-attribute-that-can-be-none">this question</a> nor <a href="http://stackoverflow.com/questions/39085672/sorting-by-multiple-values-that-can-be-none">this one</a> helped.</p>

<p>Use as key a <em>tuple</em>, like <code>(False, value)</code>. If value is None, then the tuple should be <code>(True, None)</code>.</p>

<p>Tuples are compared by their first element first, then the second, et cetera. False sorts before True. So all None values will be sorted to the end.</p>

<pre><code>def none_to_end_key(item):
    value = item.data.value if item.data else None
    return (value is None, value)

sorted(items, key=none_to_end_key)
</code></pre>

<p>Will sort all None values to the end.</p>

<p>I see now that you have tagged your question Python-2.7, then this is probably overkill. In Python 3, comparing None to an integer or string raises an exception, so you can't simply sort a list with None and other values, and something like this is needed.</p>

python python-2.7 sorting