Python3 sorts lists, dictionaries, and their nested data (JSON) format

In Python, lists and dictionaries are basic data types. These two data types will form complex data types through mutual nesting and multiple levels. Similar to the JSONdata format, sorting lists and dictionaries can actually be compared to JSONsorting.

list sort

Lists can be sorted()sorted using functions:

In [1]: color = ['White', 'Black', 'Red', 'Yellow', 'Green', 'Blue']

In [2]: sorted(color)
Out[2]: ['Black', 'Blue', 'Green', 'Red', 'White', 'Yellow']

Sort the list in descending order:

In [3]: sorted(color, reverse=True)
Out[3]: ['Yellow', 'White', 'Red', 'Green', 'Blue', 'Black']

You can also use the built-in sorting properties of lists list.sort():

In [1]: color = ['White', 'Black', 'Red', 'Yellow', 'Green', 'Blue']

In [2]: color
Out[2]: ['White', 'Black', 'Red', 'Yellow', 'Green', 'Blue']

In [3]: color.sort()

In [4]: color
Out[4]: ['Black', 'Blue', 'Green', 'Red', 'White', 'Yellow']

In [5]: color.sort(reverse=True)

In [6]: color
Out[6]: ['Yellow', 'White', 'Red', 'Green', 'Blue', 'Black']

list.sort()An attribute that only exists in lists. It will directly modify the original list and return it None(sort in place). While sorted()is applicable to any iterable object, sorted()it will be more convenient and efficient if you don't need to sort it in place.

dictionary sort

Dictionaries are sorted()sorted using functions:

In [1]: color = {
    
    'White': 1, 'Black': 2, 'Red': 3, 'Yellow': 3, 'Green': 2, 'Blue': 1}

In [2]: color
Out[2]: {
    
    'White': 1, 'Black': 2, 'Red': 3, 'Yellow': 3, 'Green': 2, 'Blue': 1}

Sort a dictionary in ascending order by its keys:

In [3]: sorted(color)
Out[3]: ['Black', 'Blue', 'Green', 'Red', 'White', 'Yellow']

sorted()By default, the function sorts the keys of the dictionary in ascending order, which is equivalent to the following form:

In [4]: sorted(color.keys(), reverse=False)
Out[4]: ['Black', 'Blue', 'Green', 'Red', 'White', 'Yellow']

Sort a dictionary in descending order by its keys:

In [5]: sorted(color, reverse=True)
Out[5]: ['Yellow', 'White', 'Red', 'Green', 'Blue', 'Black']

In [6]: sorted(color.keys(), reverse=True)
Out[6]: ['Yellow', 'White', 'Red', 'Green', 'Blue', 'Black']

Sort a dictionary's values ​​in ascending order:

In [7]: sorted(color.values())
Out[7]: [1, 1, 2, 2, 3, 3]

The result of this sorting is a list of dictionary values, so generally you need to specify a sorting algorithm, usually using lambdaa function as the sorting rule.

In is a tuple, a key, lambda x: x[1]and a value.xx[0]x[1]

In [8]: sorted(color.items(), key=lambda x: x[1])
Out[8]: 
[('White', 1),
 ('Blue', 1),
 ('Black', 2),
 ('Green', 2),
 ('Red', 3),
 ('Yellow', 3)]

After the dictionary sorting is completed, dict()the tuple can be turned back into a dictionary through the function:

In [15]: dict(sorted(color.items(), key=lambda x: x[1]))
Out[15]: {
    
    'White': 1, 'Blue': 1, 'Black': 2, 'Green': 2, 'Red': 3, 'Yellow': 3}

Before Python 3.5 (including), dictionaries did not guarantee order. Key-value pair A was inserted into the dictionary first, and key-value pair B was inserted into the dictionary later. However, when you print the Keys list of the dictionary, you will find that B may be in front of A. . But starting from Python 3.6, dictionaries become ordered.

Nested sort

The above is just a separate explanation of list and field sorting, but nested sorting is often encountered in the actual development process, so nested sorting is the focus of this article.

Through permutation and combination, we can know that there are four types of nested sorting:

Dictionary nested dictionary

In [1]: color = {
    
    
   ...:     'White': {
    
    'level': 1},
   ...:     'Black': {
    
    'level': 2},
   ...:     'Red': {
    
    'level': 3},
   ...:     'Yellow': {
    
    'level': 3},
   ...:     'Green': {
    
    'level': 2},
   ...:     'Blue': {
    
    'level': 1}
   ...: }

In [2]: color
Out[2]: 
{
    
    'White': {
    
    'level': 1},
 'Black': {
    
    'level': 2},
 'Red': {
    
    'level': 3},
 'Yellow': {
    
    'level': 3},
 'Green': {
    
    'level': 2},
 'Blue': {
    
    'level': 1}}

Sort a dictionary in ascending order by its keys:

In [3]: sorted(color.items())
Out[3]: 
[('Black', {
    
    'level': 2}),
 ('Blue', {
    
    'level': 1}),
 ('Green', {
    
    'level': 2}),
 ('Red', {
    
    'level': 3}),
 ('White', {
    
    'level': 1}),
 ('Yellow', {
    
    'level': 3})]
 
In [4]: dict(sorted(color.items()))
Out[4]: 
{
    
    'Black': {
    
    'level': 2},
 'Blue': {
    
    'level': 1},
 'Green': {
    
    'level': 2},
 'Red': {
    
    'level': 3},
 'White': {
    
    'level': 1},
 'Yellow': {
    
    'level': 3}}

Sort a dictionary in descending order by its keys:

In [5]: sorted(color.items(), key=lambda x: x[0], reverse=True)
Out[5]: 
[('Yellow', {
    
    'level': 3}),
 ('White', {
    
    'level': 1}),
 ('Red', {
    
    'level': 3}),
 ('Green', {
    
    'level': 2}),
 ('Blue', {
    
    'level': 1}),
 ('Black', {
    
    'level': 2})]

In [6]: dict(sorted(color.items(), key=lambda x: x[0], reverse=True))
Out[6]: 
{
    
    'Yellow': {
    
    'level': 3},
 'White': {
    
    'level': 1},
 'Red': {
    
    'level': 3},
 'Green': {
    
    'level': 2},
 'Blue': {
    
    'level': 1},
 'Black': {
    
    'level': 2}}

Nested list of dictionaries

In [1]: color = {
    
    
   ...:     'White': [250, 255, 251],
   ...:     'Black': [0, 2, 1],
   ...:     'Red': [255, 2, 0],
   ...:     'Yellow': [255, 254, 0],
   ...:     'Green': [1, 128, 0],
   ...:     'Blue': [0, 1, 255]
   ...: }

In [2]: color
Out[2]: 
{
    
    'White': [250, 255, 251],
 'Black': [0, 2, 1],
 'Red': [255, 2, 0],
 'Yellow': [255, 254, 0],
 'Green': [1, 128, 0],
 'Blue': [0, 1, 255]}

Sort a dictionary in ascending order by its keys:

In [3]: sorted(color.items())
Out[3]: 
[('Black', [0, 2, 1]),
 ('Blue', [0, 1, 255]),
 ('Green', [1, 128, 0]),
 ('Red', [255, 2, 0]),
 ('White', [250, 255, 251]),
 ('Yellow', [255, 254, 0])]

In [4]: dict(sorted(color.items()))
Out[4]: 
{
    
    'Black': [0, 2, 1],
 'Blue': [0, 1, 255],
 'Green': [1, 128, 0],
 'Red': [255, 2, 0],
 'White': [250, 255, 251],
 'Yellow': [255, 254, 0]}

Sort the values ​​of a list in a dictionary in ascending order:

In [5]: sorted(color.items(), key=lambda x: x[1][0])
Out[5]: 
[('Black', [0, 2, 1]),
 ('Blue', [0, 1, 255]),
 ('Green', [1, 128, 0]),
 ('White', [250, 255, 251]),
 ('Red', [255, 2, 0]),
 ('Yellow', [255, 254, 0])]

In [6]: sorted(color.items(), key=lambda x: x[1][1])
Out[6]: 
[('Blue', [0, 1, 255]),
 ('Black', [0, 2, 1]),
 ('Red', [255, 2, 0]),
 ('Green', [1, 128, 0]),
 ('Yellow', [255, 254, 0]),
 ('White', [250, 255, 251])]

In [7]: sorted(color.items(), key=lambda x: x[1][2])
Out[7]: 
[('Red', [255, 2, 0]),
 ('Yellow', [255, 254, 0]),
 ('Green', [1, 128, 0]),
 ('Black', [0, 2, 1]),
 ('White', [250, 255, 251]),
 ('Blue', [0, 1, 255])]

In lambda x: x[1][0], x[1][0]it means sorting by the first value in the list, and so on.

Sort the values ​​of a list in a dictionary in descending order:

In [8]: sorted(color.items(), key=lambda x: x[1][0], reverse=True)
Out[8]: 
[('Red', [255, 2, 0]),
 ('Yellow', [255, 254, 0]),
 ('White', [250, 255, 251]),
 ('Green', [1, 128, 0]),
 ('Black', [0, 2, 1]),
 ('Blue', [0, 1, 255])]

List nested list

In [1]: color = [['White', 2], ['Black', 3], ['Red', 4],['White', 1], ['Black', 2], ['Red', 3]]

In [2]: color
Out[2]: 
[['White', 2],
 ['Black', 3],
 ['Red', 4],
 ['White', 1],
 ['Black', 2],
 ['Red', 3]]

In [3]: sorted(color)
Out[3]: 
[['Black', 2],
 ['Black', 3],
 ['Red', 3],
 ['Red', 4],
 ['White', 1],
 ['White', 2]]

In [4]: sorted(color, reverse=True)
Out[4]: 
[['White', 2],
 ['White', 1],
 ['Red', 4],
 ['Red', 3],
 ['Black', 3],
 ['Black', 2]]

List nested dictionary

In [1]: colors = [
   ...:     {
    
    'color': 'White', 'level': 2},
   ...:     {
    
    'color': 'Black', 'level': 3},
   ...:     {
    
    'color': 'Red', 'level': 4},
   ...:     {
    
    'color': 'White', 'level': 1},
   ...:     {
    
    'color': 'Black', 'level': 2},
   ...:     {
    
    'color': 'Red', 'level': 3}
   ...: ]

In [2]: colors
Out[2]: 
[{
    
    'color': 'White', 'level': 2},
 {
    
    'color': 'Black', 'level': 3},
 {
    
    'color': 'Red', 'level': 4},
 {
    
    'color': 'White', 'level': 1},
 {
    
    'color': 'Black', 'level': 2},
 {
    
    'color': 'Red', 'level': 3}]

Sort the fields of each dictionary in the list color(single-level sorting):

In [3]: sorted(colors, key=lambda x: x['color'])
Out[3]: 
[{
    
    'color': 'Black', 'level': 3},
 {
    
    'color': 'Black', 'level': 2},
 {
    
    'color': 'Red', 'level': 4},
 {
    
    'color': 'Red', 'level': 3},
 {
    
    'color': 'White', 'level': 2},
 {
    
    'color': 'White', 'level': 1}]

colorSort the fields of each dictionary in the list and then levelsort the fields (multi-level sorting):

In [4]: sorted(colors, key=lambda x: (x['color'], x['level']))
Out[4]: 
[{
    
    'color': 'Black', 'level': 2},
 {
    
    'color': 'Black', 'level': 3},
 {
    
    'color': 'Red', 'level': 3},
 {
    
    'color': 'Red', 'level': 4},
 {
    
    'color': 'White', 'level': 1},
 {
    
    'color': 'White', 'level': 2}]

Reference articles:
https://docs.python.org/zh-cn/3/howto/sorting.html
https://www.kingname.info/2019/07/13/python-dict
https://blog.csdn .net/ray_up/article/details/42084863

Guess you like

Origin blog.csdn.net/yilovexing/article/details/132556931