Python: sorting dictionary list

 Reference: https://www.runoob.com/python3/python-sort-dictionaries-by-key-or-value.html

if __name__ == '__main__':
    list = []
    for i in range(10):
        dict_time = {"time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
        list.append(dict_time)
        time.sleep(1)
    print(list)
    print(sorted(list, key=lambda i: i['time'], reverse=True))

The sorted() function sorts all iterable objects, the key is the element used for comparison

Lambda is used for anonymous functions, it is a fixed wording, do not write other words

i represents an element in the list, here, it represents a dictionary, i is just a temporary name, you can use any name; the command i['time'] means to follow the'time' in the list dictionary Sort. Default ascending order, reverse=True means descending order 

The output of the above code:                                     

[{'time': '2020-09-18 18:04:08'}, {'time': '2020-09-18 18:04:09'}, {'time': '2020-09-18 18:04:10'}, {'time': '2020-09-18 18:04:11'}, {'time': '2020-09-18 18:04:12'}, {'time': '2020-09-18 18:04:13'}, {'time': '2020-09-18 18:04:14'}, {'time': '2020-09-18 18:04:15'}, {'time': '2020-09-18 18:04:16'}, {'time': '2020-09-18 18:04:17'}]
[{'time': '2020-09-18 18:04:17'}, {'time': '2020-09-18 18:04:16'}, {'time': '2020-09-18 18:04:15'}, {'time': '2020-09-18 18:04:14'}, {'time': '2020-09-18 18:04:13'}, {'time': '2020-09-18 18:04:12'}, {'time': '2020-09-18 18:04:11'}, {'time': '2020-09-18 18:04:10'}, {'time': '2020-09-18 18:04:09'}, {'time': '2020-09-18 18:04:08'}]

The following is a detailed explanation of the sorted sorting method: (thanks: https://blog.csdn.net/cxcxrs/article/details/82459800#%E4%B8%80%E3%80%81sorted%E9%AB%98%E9 %98%B6%E5%87%BD%E6%95%B0 )

1. The  syntax format of sorted higher-order function:   sorted (iterable object, key=function name, reverse=False/True)

     Function: From the iterable object, one element is taken out in sequence, and the element is sorted according to the arrangement basis specified by the key.

     Iterable objects: objects that can take values ​​in sequence, such as collections, sequences (lists, strings, tuples), dictionaries, etc.

     key  : is the basis of the list sorting. Generally, you can customize a function to return the sorting basis, and then bind the function name to the key.

     reverse : Translated as reverse, reverse is equal to False by default, sorting from small to large. When equal to True, sort from largest to smallest.

 

2.  The format of anonymous function lambda:     function name = lambda [formal parameter 1, formal parameter 2,...]:,   return the result of the operation statement block and bind it to the function name.

For example:  key=lambda x: x[1]       

            X : the dictionary corresponding to the set of a tuple , for example: dict_items ([( 'a' , 1), ( 'c', 3), ( 'b', 2)]) in the ( 'a', 1 ) Or ('c', 3) or ('b', 2)

            x[1] : Returns the second element in x, which is the value in the key-value pair tuple . dict_items([('a', 1), ('c', 3), ('b', 2)]) 1 or 2 or 3

note:

  (1) Do not use the dictionary d for the iterable objects  in the sorted function , so that only the keys of the dictionary d can be iterated. Only use d.items() to iterate out the key-value pairs of the dictionary.

    Example: d_order=sorted(d,key=lambda x:x[1],reverse=False) cannot be used

            要用 d_order=sorted(d.items(),key=lambda x:x[1],reverse=False)

  (2) After the  sorted function is sorted, it is necessary to bind an object (assignment), for example: d_order=sorted(d.items(),key=lambda x:x[1],reverse=False).

     Because the dictionary is an unordered type, use the sorted function to sort the order without binding d_order, the dictionary will automatically shuffle the order.

 

 

Guess you like

Origin blog.csdn.net/weixin_38676276/article/details/108670611