Reverse: Indicate ascending or descending, true--descending, false--ascending (default);1 Importoperator; 2 #Sort in dictionary3 defsortdict ():4dic={'a': 1,'F': 2,'C': 3,'h': 0};5 #function Prototype: sorted (dic,value,reverse)6 #sort Ascending by key in dictionary7 Print("Press the key to sort the result in ascending order:",8Sorted (Dic.items (), Key=operator.itemgetter (0), reverse=False));9 #sort Descending by key in dictionaryTen Print("The keys are sorted in descending order:", OneSorted (Dic.items (), Key=operator.itemgetter (0), reverse=True)); A #sort Ascending by values in a dictionary - Print("ascending Sort by value results in:", -Sorted (Dic.items (), Key=operator.itemgetter (1), reverse=False)); the #Sort Descending by a value in a dictionary - Print("descending Sort by value results in:", -Sorted (Dic.items (), Key=operator.itemgetter (1), reverse=true));
The result of the operation is:
1>>>ImportRandmatrix;2>>>sortdict ()3The key is sorted in ascending order: [('a', 1), ('C', 3), ('F', 2), ('h', 0)]4The key is sorted in descending order: [('h', 0), ('F', 2), ('C', 3), ('a', 1)]5Ascending sort by value results in: [('h', 0), ('a', 1), ('F', 2), ('C', 3)]6The descending sort by value results in the following: [('C', 3), ('F', 2), ('a', 1), ('h', 0)]
Iteritems () function: