David Dahan
David Dahan

Reputation: 11152

Sorting Python lists of objects by keys with different names

I used to merge and sort 2 lists of objects that both have a "created" attributes which is a datetime.

I dit it this way and this worked well:

all_events = sorted(
    chain(list1, list2),
        key=attrgetter('created'))

Now, I'd like to add a 3rd list in the sort. The problem is the datetime attribute of objects in that 3rd list is not named 'created'.

How would you do to sort the 3 lists in that case?

Thank you.

Upvotes: 0

Views: 87

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121366

Use a lambda to get the attribute with fallback:

all_events = sorted(
    chain(list1, list2, list3),
    key=lambda o: getattr(o, 'created', getattr(o, 'otherattribute', None))

This will try to get either attribute, preferring 'created'.

Upvotes: 3

Related Questions