Because a job on core Python programming is 7-3
The keys and values of a dictionary must be displayed simultaneously and sorted by keys.
After I finish, what if I want to sort by value? Or when multiple tuple are sorted, what elements are specified as keywords?
Google found the answer and noted down:
Solution 2:
Method 1Use Lambda syntax.
PythonSupports an interesting syntax that allows you to quickly define the smallest function of a single row. These are calledLambdaFromLISPBorrowed functions can be used in any place where functions are needed.
>>> G = Lambda X: x * 2 # This defines a function and uses g to record it. <br/> G (3) <br/> 6 <br/> (lambda X: x * 2) (3) # This also defines a function, no name <br/> 6 <br/>
So this question can be used:
A = {'Port': '000000', 'protocol': 'http', 'address': '2017. 101.1.22 ', 'name': 'Thy', 'pwd': 'athy '} </P> <p> B = zip (. keys (),. values () # pulls a list composed of tuple pairs </P> <p> sorted (B, key = Lambda item: item [1]) <br/> # pass each tuple In the ZIP file to the lambda function and mark it as an item. assign item [1], that is, the second element of the tuple, as the return value to the key.
Result:[('Address', '2017. 101.1.22 '), ('Port', '123'), ('pwd', 'athy'), ('protocol', 'http'), ('name ', 'Thy ')]
Method 2Is the itemgetter function of the operator module.
A = {'Port': '000000', 'protocol': 'http', 'address': '2017. 101.1.22 ', 'name': 'Thy', 'pwd': 'athy '} </P> <p> B = zip (. keys (),. values () # The list composed of tuple pairs </P> <p> from operator import itemgetter <br/> sorted (B, key = itemgetter (1 ))
Of course the results are the same.
Finally, let's take a look at the default parameters (that isSorted (B)) Result:
[('Address', '2017. 101.1.22 '), ('name', 'Thy'), ('Port', '123'), ('protocol', 'http'), ('pwd ', 'athy ')]
Among them, I prefer Lambda's syntax. After all, it is solved at the language level. It is said that Lambda is also introduced in the boost library, which is really good!