Wang Nick
Wang Nick

Reputation: 495

sort list of dicts by different keys in python

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

Answers (1)

Eugene Yarmash
Eugene Yarmash

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

Related Questions