Posts

Showing posts with the label Python

Sort the dictionary based on values

Dictionary to sort based on the values names = { 'ZIZ' : 8 , 'RGY' : 2 , 'TYM' : 1 , 'SDC' : 10 , 'VUW' : 2 , 'JCQ' : 2 , \ ... 'PXN' : 2 , 'JGU' : 3 , 'CGB' : 1 , 'BHB' : 10 } print (names) { 'TYM' : 1 , 'BHB' : 10 , 'JCQ' : 2 , 'SDC' : 10 , 'RGY' : 2 ,\ 'VUW' : 2 , 'CGB' : 1 , 'ZIZ' : 8 , 'JGU' : 3 , 'PXN' : 2 } Sort the dictionary using a lambda function sorted (names, key = lambda x:names[x]) [ 'TYM' , 'CGB' , 'JCQ' , 'RGY' , 'VUW' , 'PXN' , 'JGU' , 'ZIZ' , 'BHB' , 'SDC' ] Sort the dictionary using a function # Function to extract value from a dictionary def values ( x ): return names[x] sorted (names, key = values) [ 'TYM' , 'CGB...