I have a list of Python objects that I want to sort by a specific attribute of each object:
>>> ut
[Tag(name="toe", count=10), Tag(name="leg", count=2), ...]
How do I sort the list by .count
in descending order?
8 s
# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)
# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)
More on sorting by keys.