There is a list of nested dictionaries: [{"a": 5}, {"B":4}, {"C": 1},{"e": 2}, {"D ": 3}], their values are not the same, now you want to sort by values:
< Span style= "COLOR: #800000" > < Span style= "COLOR: #800000" > idea: For a value sort, first take the value out of the dictionary, Place this value in a dictionary and a smaller position so that it can be sorted by value
< Span style= "COLOR: #800000" > < Span style= "COLOR: #800000" > Sorting by different keys is the same.
Specific code implementation
1 #define a method to remove a value from a dictionary2 defGet_val (_dict):3val =list (_dict.values ()) [0] # Sort by value: Change . VALUES () to. Keys () OK4 returnVal5 6 7 #Defining Collations8 defBoff_sort (_list):9n =Len (_list)Ten forIinchRange (n-1): One forJinchRange (n-1-i): A ifGet_val (_list[j]) > Get_val (_list[j+1]):#to sort the values in the dictionary -_LIST[J], _list[j+1] = _list[j+1], _list[j] - the - if __name__=='__main__': -Li = [{"a": 5}, {"b": 4}, {"C": 1},{"e": 2}, {"D": 3}] - Boff_sort (LI) + Print(LI) - #The run result is [{' C ': 1}, {' E ': 2}, {' d ': 3}, {' B ': 4}, {' A ': 5}]
When you sort the same key, it's easy to use a lambda function to get it done.
Python is sorted according to the value of the dictionary: