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>Just filter the None values first before sending them to sorted.</p>

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

<p>And if you really want the None items too, you can do something like this:</p>

<pre><code># items already defined with values
new_items_list = sorted(filter(None, items), key=attrgetter('data.value'))
new_items_list.extend([None] * (len(items) - len(new_items_list)))
</code></pre>

<p>However, I am not sure whether you really need the None items.</p>

<p>EDIT: Fixed the end code which will retain the None items.</p>

python python-2.7 sorting