dabadaba dabadaba - 1 year ago 57
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
, so I'd normally go:

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

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

How do you usually deal with scenarios like this?

PS: neither this question nor this one helped.

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