Sort a python dictionary
fruits = {'apple':12 , 'banana':9 , 'orange':15 , 'mango':5 , 'grape':20}
## sort based on <value>
fruits_lst = sorted(fruits.items() , key= lambda value : value[1] , reverse=True )
fruits = {}
for key , value in fruits_lst:
fruits[key] = value
print(fruits)
Output : {'grape': 20, 'orange': 15, 'apple': 12, 'banana': 9, 'mango': 5}
## sort based on <key>
fruits_lst = sorted(fruits.items() , key= lambda key : key[0] , reverse=True )
fruits = {}
for key , value in fruits_lst:
fruits[key] = value
print(fruits){'orange': 15, 'mango': 5, 'grape': 20, 'banana': 9, 'apple': 12}
Comments
Post a Comment