Call directly sorted(iterable,key,reverse)
1. Output key only :
>>> test_dict = {
'a':1, 's':5, 'd':2, 'f':3}
>>> sorted(test_dict.keys())
['a', 'd', 'f', 's']
2. Key values are output at the same time
>>> sorted(test_dict.items(), key=lambda item:item[0])
[('a', 1), ('d', 2), ('f', 3), ('s', 5)]
Method 1 :sorted Methodical key Parameters use lambda obtain value Value to sort
>>> sorted(test_dict.items(), key=lambda item:item[1])
[('a', 1), ('d', 2), ('f', 3), ('s', 5)]
>>> sorted(test_dict.items(), key=lambda item:item[1], reverse = True)
[('s', 5), ('f', 3), ('d', 2), ('a', 1)]
Method 2 : Use operator Of itemgetter Sort
itemgetter Function is used to get the data of which location of the object , The parameter is the sequence number value representing the position .
>>> import operator
>>> sorted(test_dict.items(), key=operator.itemgetter(1))
[('a', 1), ('d', 2), ('f', 3), ('s', 5)]
>>> sorted(test_dict.items(), key=operator.itemgetter(1), reverse = True)
[('s', 5), ('f', 3), ('d', 2), ('a', 1)]