In this lesson, you’ll learn how to sort iterables in Python. You can either use the sorted()
built-in function, or .sort()
method. You can pass in the optional key
parameter to specify how to sort the iterable, and you can reverse with the reverse
parameter:
>>> animals = [{'type': 'cat', 'name': 'Stephanie', 'age': 8}, {'type': 'dog', 'name': 'Devon', 'age': 3}, {'type': 'rhino', 'name': 'Moe', 'age': 5}]
>>> sorted(animals, key=lambda animal: animal['age], reverse=True)
[{'type': 'cat', 'name': 'Stephanie', 'age': 8}, {'type': 'rhino', 'name': 'Moe', 'age': 5}, {'type': 'dog', 'name': 'Devon', 'age': 3}]
If you want to learn more, check out Sorting Data With Python.
Piotr on April 25, 2020
Isn’t it somewhat wrong to suggest to use sorting to get the oldest animal in your example?
I don’t reckon the interviewer would be impressed to see a O(n log n) solution instead of simple iteration over a list resulting in a O(n).