dic = {'a' : 31,'b' : 5, 'c' : 3, 'd' : 4, '33' : 56, 'd' : 0}
I want to sort the dic value from large to small (values are integers).
The writing method is as follows: sorted((), key=lambdad:d[1], reverse = False )
See firstlambdaWhat does a function mean?
>>> f=lambdax:x+1
>>>f(2)
3
It's very simple, x is the parameter, and x+1 is the return value of the function.
That()What is it? existsortedHow does it have a relationship with lambda in the function? Look at my debugging code:
>>> for i indic:
... print i[0], i //i[0]The first character
>>>()
<dictionary-itemiteratorobject at 0xb7ed1464> //Return an object
>>>type(())
<type'dictionary-itemiterator'>
>>> printsorted((), key=lambda a:a[0]) //() Returns a Yuanzu
[('33', 56), ('a', 31), ('b', 5), ('c', 3),('d', 0)]
>>> printsorted((), key=lambda a:a[1])
[('d', 0), ('c', 3), ('b', 5), ('a', 31),('33', 56)]
>>> printsorted((), key=lambda a:a[0], reverse =False)
[('33', 56), ('a', 31), ('b', 5), ('c', 3),('d', 0)]
() //Return a tuple, each tuple contains a pair of (key, value)
key=lambda a:a[0] //key is a parameter of the sorted function
//What is lambda a:a[0]? We put lambda sss:sss[0] and the result is the same. It is just the parameter passed in the previous one, and the name doesn't matter.
sorted((), key=lambda d:d[1],reverse = False )
The whole meaning is to pass on the original ancestors in (), but we only need the value in it, that is, d[1](d[0] is key), so key=lambda d:d[1] is sorted according to the value.
If you want to sort by key, just key=lambda d:d[0], reverse= False(True) means whether to turn on reverse order sorting