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', 'RGY', 'VUW', 'JCQ', 'PXN', 'JGU', 'ZIZ', 'SDC', 'BHB']

Popular posts from this blog

How to get the range of acceptable value of arithmetic types.