python dictionary sorting method

[Dictionary] in python is an unordered variable sequence of "key-value pairs".
In practical applications, sorting dictionary type data is a relatively common operation.
The Python built-in function sorted() is mainly used, which can sort all iterable objects.
The syntax of sorted() is as follows (python3):

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

Parameter description:

parameter Definition
iterable Iterable objects are objects that can be iterated using a for loop.
key It is mainly used for comparing elements and has only one parameter. The specific function parameters are taken from the iterable object and are used to specify an element in the iterable object for sorting.
reverse Sorting rules, reverse=False ascending order (default), reverse=True descending order.

The following summarizes the two most common uses of the sorted() function when sorting dictionaries.

The first: the most common single dictionary format data sorting

Single-level dictionary sorting is used, for example:

# 字典排序
a = {
    
    'a': 3, 'c': 89, 'b': 0, 'd': 34}
# 按照字典的值进行排序
a1 = sorted(a.items(), key=lambda x: x[1])
# 按照字典的键进行排序
a2 = sorted(a.items(), key=lambda x: x[0])
print('按值排序后结果', a1)
print('按键排序后结果', a2)
print('结果转为字典格式', dict(a1))
print('结果转为字典格式', dict(a2))

Insert image description here
Principle: Each element in the list [('a', 3), ('c', 89), ('b',0), ('d', 34)] returned by a.items(), As parameters of the anonymous function (lambda), x[0] is sorted by "key", and x[1] is sorted by "value"; the returned result is a new list, which can be converted to dictionary format through the dict() function.

Second type: dictionary list sorting

Data in a single dictionary format nested in a list is more common in practical applications.
The sorting method for data in this format is as follows:

b = [{
    
    'name': 'lee', 'age': 23}, {
    
    'name': 'lam', 'age': 12}, {
    
    'name': 'lam', 'age': 18}]
b1 = sorted(b, key=lambda x: x['name'])
b2 = sorted(b, key=lambda x: x['age'],  reverse=True)
b3 = sorted(b, key=lambda x: (x['name'], -x['age']))
print('按name排序结果:', b1)
print('按age排序结果:', b2)
print('name相同按age降序排列:', b3)

Insert image description here
Principle: Use each dictionary element in list b as the parameter of the anonymous function, and then use the key to take the elements in the dictionary as the sorting condition as needed. For example, x['name'] uses the value corresponding to the name key to sort.

-end-

Guess you like

Origin blog.csdn.net/LHJCSDNYL/article/details/122525942