[Python] How to sort dict in list and instance in list

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.

Python version that has been confirmed to work

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

[Python] How to sort dict in list and instance in list
How to use is and == in Python
How to clear tuples in a list (Python)
How to generate permutations in Python and C ++
[Python] How to sort instances by instance variables
How to plot autocorrelation and partial autocorrelation in python
How to remove duplicate elements in Python3 list
[Python] How to use list 1
How to develop in Python
[Python] How to output the list values in order
[Python] How to do PCA in Python
How to collect images in Python
How to use SQLite in Python
[Python] How to use list 3 Added
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
How to handle Japanese in Python
How to swap elements in an array in Python, and how to reverse an array.
Sort and output the elements in the list as elements and multiples in Python.
Useful tricks related to list and for statements in Python
Comparison of how to use higher-order functions in Python 2 and 3
How to get the last (last) value in a list in Python
How to get a list of built-in exceptions in python
How to execute external shell scripts and commands in python
How to log in to AtCoder with Python and submit automatically
How to achieve access by attribute and retention of insertion order in Python dict
How to store Python function in Value of dictionary (dict) and call function according to Key
How to package and distribute Python scripts
[Introduction to Python] How to use class in Python?
How to install OpenCV on Cloud9 and run it in Python
How to access environment variables in Python
How to compare lists and retrieve common elements in a list
How to dynamically define variables in Python
How to install and use pandas_datareader [Python]
How to do R chartr () in Python
[Itertools.permutations] How to put permutations in Python
How to create an instance of a particular class from dict using __new__ () in python
How to use functions in separate files Perl and Python versions
How to work with BigQuery in Python
[Python] How to delete rows and columns in a table (list of drop method options)
Difference between append and + = in Python list
Difference in how to write if statement between ruby ​​and python
How to display multiplication table in python
How to extract polygon area in Python
How to check opencv version in python
python: How to use locals () and globals ()
[ROS2] How to describe remap and parameter in python format launch
How to switch python versions in cloud9
How to adjust image contrast in Python
How to use __slots__ in Python class
How to dynamically zero pad in Python
[Python] How to calculate MAE and RMSE
How to use Python zip and enumerate
Summary of how to use Python list
How to use regular expressions in Python
How to delete multiple specified positions (indexes) in a Python list
I was addicted to confusing class variables and instance variables in Python
How to display Hello world in python
How to write Ruby to_s in Python