[Python] Sort collection types

Summarize how to sort Python collection types.

list

The first is to use the list method. The sort method does not take a return value and rewrites the original list. By default, it is sorted in ascending order.

>>> a = [8, 1, 5, 3, 6]
>>> a.sort()
>>> a
[1, 3, 5, 6, 8]

If you want to sort in descending order, set the reverse keyword of the argument to True.

>>> a = [8, 1, 5, 3, 6]
>>> a.sort(reverse=True)
>>> a
[8, 6, 5, 3, 1]

The second is to use the sorted function. The sorted function returns a sorted list.

>>> a = [8, 1, 5, 3, 6]
>>> sorted(a)
[1, 3, 5, 6, 8]

Even with the sorted function, you can sort in descending order by setting the reverse keyword to True.

>>> a = [8, 1, 5, 3, 6]
>>> sorted(a, reverse=True)
[8, 6, 5, 3, 1]

dictionary

Python dictionaries cannot be sorted because the order is not guaranteed. Passing a dictionary as an argument to the sorted function returns a sorted list of keys only.

>>> b = {'Matsui': 55, 'Ichiroh': 51, 'Kuroda': 18}
>>> sorted(b)
['Ichiroh', 'Kuroda', 'Matsui']

The items method returns a nested tuple in the list. At this time, it is sorted by key.

>>> b = {'Matsui': 55, 'Ichiroh': 51, 'Kuroda': 18}
>>> sorted( b.items() )
[('Ichiroh', 51), ('Kuroda', 18), ('Matsui', 55)]

If you want to sort by value, use key parameter and lambda function.

>>> b = {'Matsui': 55, 'Ichiroh': 51, 'Kuroda': 18}
>>> sorted(b.items(), key=lambda x:x[1])
[('Kuroda', 18), ('Ichiroh', 51), ('Matsui', 55)]

If you want to sort while maintaining the structure, use OrderedDict. * Added / corrected as pointed out by @shiracamus.

>>> b = {'Matsui': 55, 'Ichiroh': 51, 'Kuroda': 18}
>>> b
{'Ichiroh': 51, 'Matsui': 55, 'Kuroda': 18}
>>> from collections import OrderedDict
>>> c = OrderedDict(sorted(b.items(), key=lambda x:x[1]))
>>> c
OrderedDict([('Kuroda', 18), ('Ichiroh', 51), ('Matsui', 55)])
>>> c.values()
[18, 51, 55]
>>> c.keys()
['Kuroda', 'Ichiroh', 'Matsui']

Tuple

Tuples are immutable objects and cannot be sorted exactly, but they can be achieved by using the sorted and tuple functions.

>>> d = (8, 1, 5, 3, 6)
>>> tuple( sorted(d) )
(1, 3, 5, 6, 8)

Please also refer to the Official page.

Recommended Posts

[Python] Sort collection types
[Python] Sort
Python # sort
python (3) dominer ORM collection
Bubble sort in Python
Python self-made class sort
python small story collection
[Memo] Python3 list sort
Python sort cheat sheet
Custom sort in Python3
Organize types in Python
Sort Python module imports alphabetically
Naturally sort Path in Python
Python basic dict sort order
Sort huge files with python
python in mongodb in descending sort
python snippet collection with cinema4d
Python beginners organize bubble sort
Image Processing Collection in Python
Sort by date in python
About Python sort () and reverse ()
[Python] Random processing (create, select, sort)
[Python] Sort iterable by multiple conditions
Python
Perform Scala-like collection operations in Python
Sort large text files in Python
[Python] One-liner Stalin sort with 50 characters
sort
Generate a first class collection in Python
New in Python 3.9 (2)-Sort directed acyclic graphs in Python
Python numbers, strings, list types (Python learning memo ①)
[Reinventing the wheel] Human-powered tournament sort [Python]
Convert Python date types to RFC822 format
Scientific Programming Petit Tech Collection in Python
Implemented Stooge sort in Python3 (Bubble sort & Quicksort)
[Python] I searched for various types! (Typing)