dabadaba dabadaba - 2 months ago 5
Python Question

Python sorting by attributes that can be None

Let's say I have a list of items I want to sort:

items = [ item1, item2, item3 ]
. The attribute I want to use to sort them is
item.data.value
, so I'd normally go:

sorted(items, key=attrgetter('data.value'))


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

How do you usually deal with scenarios like this?

PS: neither this question nor this one helped.

Answer
sorted(items, key=lambda i: i.data.value if i.data else 0)
Comments