we know that Python's built-in dictionary data types are unordered, with key to get the corresponding Value. But sometimes we need to sort the output of the item in the dictionary, depending on the key, or it may be sorted by Value. How many ways can the dictionary content be sorted out? Here are some wonderful solutions. #the simplest way to do this is to sort by the key value:defsortedDictValues1 (adict): Items=adict.items () Items.Sort ( )return[value forkey, valueinchitems]#another sort by the key value, seemingly faster than the previous Speed.defsortedDictValues2 (adict): Keys=Adict.keys () Keys.sort ( )return[dict[key] forKeyinchkeys]#or Sort by key value, which is said to be faster ... And when the key is a tuple, it still applies.defsortedDictValues3 (adict): Keys=Adict.keys () Keys.sort ( )returnmap (adict.get, Keys)#a line of statements is done:[(k,di[k]) forKinchSorted (di.keys ())]#to sort by value, first put the key and value exchange position of item into a list, and then sort by the first value of each element of the list, that is , the value of the original value:defsort_by_value (d): Items=d.items () Backitems=[[v[1],v[0]] forVinchItems]backitems.sort ()return[backitems[i][1] forIinchRange (0,len (backitems))]#or a line to fix:[v forVinchSorted (di.values ())]#use lambda expressions to sort and be more flexible:Sorted (d.items (),Lambdax, y:cmp (x[1], y[1]), or reverse order: sorted (d.items (),Lambdax, y:cmp (x[1], y[1]), reverse=True)#Sort by the key= parameter of the sorted function:#Sort by KeyPrintSorted (dict1.items (), key=Lambdad:d[0])#Sort by ValuePrintSorted (dict1.items (), key=LambdaD:d[1]) Below are the help documents for Python's built-in sorted function: sorted (...) Sorted (iterable, CMP=none, key=none, reverse=false)--new sorted list look at the above so many kinds of dictionary sorting methods, in fact, their core ideas are the same, that is, the elements in the dictionary separated out into a list, the list sort, thus, The ordering of dictionary is implemented INDIRECTLY. This "element" can be either Key,value or Item. #################################################################################A up-and-down sort by value can be used with L= Sorted (d.items (), key=LambdaD:d[1]) If the version low does not support sorted to put Key,value in a list with a tuple L=[]l.append ((akey,avalue)) ... Use the sort () l.sort (Lambdaa,b:cmp (a[1],b[1])) (cmp pre-plus "-" means descending sort)
Go: python dict sorted by value