Summarize how to sort Python collection types.
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]
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']
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