Reputation: 495
here is the list of dict I have:
[{'title': 'C'}, {'contentTitle':'B'}, {'title': 'A'}]
In python, is it possible to write a comparator to sort the list, which would first look value under title
and if there is no title
, use the value under contentTitle
Upvotes: 1
Views: 84
Reputation: 149823
You can use dict.get()
to look up a key without raising an exception:
>>> lst = [{'title': 'C'}, {'contentTitle':'B'}, {'title': 'A'}]
>>> sorted(lst, key=lambda x: x.get("title") or x.get("contentTitle"))
[{'title': 'A'}, {'contentTitle': 'B'}, {'title': 'C'}]
Upvotes: 3