Python tutorial sorting method resolution by dictionary key or value

  • 2021-11-30 00:58:48
  • OfStack

Python sorted () Function

The sorted () function sorts all iterable objects

sorted syntax:

sorted(iterable, key=None, reverse=False)

Parameter description:

iterable -Iterable objects.

key -Mainly used for comparison elements, only one parameter, the specific function parameters are taken from the iterable object, specify the iterable object in one element to sort.

reverse -Collation, reverse = True descending, reverse = False ascending (default).

1. Sort the dictionary keys (key)


dir_info= {'a':1,'d':8,'c':3,'b':5}
# Press the dictionary button ( key ) (default from small to large) 
dir_sort = sorted(dir_info.items(),key=lambda x:x[0])
print(dir_sort)

Output:
[('a', 1), ('b', 5), ('c', 3), ('d', 8)]

Direct key sorting of dictionaries


sorted({'a':1,'d':8,'c':3,'b':5}.keys())

2. Sort the dictionary by value (value)


dir_info= {'a':1,'d':8,'c':3,'b':5}
# Press the dictionary button ( key ) (default from small to large) 
dir_sort = sorted(dir_info.items(),key=lambda x:x[1])
print(dir_sort)

Output result
[('a', 1), ('c', 3), ('b', 5), ('d', 8)]

Direct value sorting of dictionaries


sorted({'a':1,'d':8,'c':3,'b':5}.values())

Analysis:

dir_info.items() key and value parameters of the dictionary are obtained

dir_info[0] Indicates sorting by element 1

dir_info[1] Indicates sorting by element 2

For ease of understanding, give another example


person_info = [('zhangsan', ' Male ', 15), ('lisi', ' Male ', 12), ('wangwu', ' Male ', 10),]
person_sort = sorted(person_info, key=lambda x: x[2])
print(person_sort)

Output:
[('wangwu', 'Male', 10), ('lisi', 'Male', 12), ('zhangsan', 'Male', 15)]

Of course, the forms of key are also various
For example:

1. Sort by String Length


key = lambda x:len(x)

2. First follow element 1, then follow element 2:


key = lambda x : (x[0] , x[1])

Extension:

Sort a 1 part of the data in the list as a key (select the element that iconic can be used for sorting as a condition)


list_info = ['test-10.txt','test-11.txt','test-22.txt','test-14.txt','test-3.txt','test-20.txt']
list_sort = sorted(list_info, key=lambda d : int(d.split('-')[1].split('.')[0]))
print(list_sort)

Output result
['test-3.txt', 'test-10.txt', 'test-11.txt', 'test-14.txt', 'test-20.txt', 'test-22.txt']

The above is the Python tutorial according to the dictionary key or value sorting method analysis of the details, more about Python according to the dictionary key or value sorting information please pay attention to other related articles on this site!


Related articles: