Sorting lists is common, but here's how to sort dict in list and instance in list.
All sorts are in ascending order.
The sort uses the built-in function sorted
.
If you don't use the standard library dataclasses, it should work with 3.6 or something.
dict in list
In the case of dict in list, it is necessary to specify the key argument of the sorted function.
You can use lambda when specifying the key and use lambda x: x ['a']
as an anonymous function, but according to the official, it seems that it is faster to use the item getter of the standard library operator (I have not verified it, so it is nothing. I can't say that).
https://docs.python.org/ja/3/howto/sorting.html#operator-module-functions
Python provides fast and easy-to-use accessor functions. The operator module has itemgetter (), attrgetter () and methodcaller () functions.
from operator import itemgetter
person_list = [{'name': 'a', 'age': 4}, {'name': 'b', 'age': 3}, {'name': 'c', 'age': 10}, {'name': 'd', 'age': 2}, {'name': 'e', 'age': 1}]
sorted(person_list, key=itemgetter('age'))
[{'name': 'e', 'age': 1},
{'name': 'd', 'age': 2},
{'name': 'b', 'age': 3},
{'name': 'a', 'age': 4},
{'name': 'c', 'age': 10}]
instance in list
As with dict in list, specify the parameters you want to sort in the key argument of the sorted function. For instance, use attr letter.
Once you create a dict in list with sources and then create an instance with list (map (...)), there is no deep meaning. I just wanted to make it easier by diverting the person_list used in the dict in list.
from dataclasses import dataclass
from operator import attrgetter
@dataclass
class Person:
name: str
age: int
sources = [{'name': 'a', 'age': 4}, {'name': 'b', 'age': 3}, {'name': 'c', 'age': 10}, {'name': 'd', 'age': 2}, {'name': 'e', 'age': 1}]
person_list = list(map(lambda x: Person(**x), sources))
sorted(person_list, key=attrgetter('age'))
[Person(name='e', age=1),
Person(name='d', age=2),
Person(name='b', age=3),
Person(name='a', age=4),
Person(name='c', age=10)]
If you want to sort in descending order, set the reverse argument of the sorted function to True.
Reference
Recommended Posts