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
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'}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.