1, Key sorting
Method 1: The simplest way to arrange the elements (Key/value pairs) and then pick out the values. The items method of the dictionary returns a list of tuples in which each tuple contains a pair of items-the key and the corresponding value. The sort () method can be sorted at this time. def sortedDictValues1 (adict):
Items = Adict.items ()
Items.Sort ()
return [Value for key, value in items]
Method 2: Use the permutation key (key) way, pick out the value, speed is faster than Method 1. The Dictionary object's keys () method returns a list of all the key values in the dictionary, in a random order. You need to sort by using the sort () method on the returned list of key values. def sortedDictValues1 (adict):
Keys = Adict.keys ()
Keys.sort ()
return [Adict[key] for key in keys]
Method 3: Through the mapping method to more effectively perform the last step def sortedDictValues1 (adict):
Keys = Adict.keys ()
Keys.sort ()
return Map (Adict.get,keys)
Method 4: Sort the dictionary keys, return them in the form of a tuple list, and use a lambda function.
Sorted (iterable[, cmp[, key[, reverse]]]
CMP and key generally use lambda
Such as:
>>> d={"OK": 1, "No": 2}
Sort the dictionary keys and return them in the form of a tuple list
>>> Sorted (D.items (), Key=lambda d:d[0])
[(' No ', 2), (' OK ', 1)]
2, sorted by value
Sort the dictionary by value and return it in the form of a tuple list
Sorted (Dict.items (), Key=lambda d:d[1],reverse=true)
[(' OK ', 1), (' No ', 2)]