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

Popular posts from this blog

SCD 2 Using Merge statement in SQL server

Flatten / Parsing XML using Azure ADF (Azure data factory)

Integer division to float division in SQL server