Wednesday, 15 December 2021

Python-Slip 29-Write a Python script to sort (ascending and descending) a dictionary by key and Value.

 Write a Python script to sort (ascending and descending) a dictionary by key and Value.

# Dictionary for Fruits and price

# item as key & price as value

 

#Sorting Dictionary by Key in Ascending Order

data = {'banana': 80,'cherry': 200,'apple': 60,'grapes':120}

 

# Sorting on the basis of key in alphabetically ascending order

sorted_result = sorted(data.items())

print("Sorting on the basis of key in alphabetically ascending order:-")

print(sorted_result)

 

#Sorting Dictionary by Key in Descending Order

sorted_result = sorted(data.items(), reverse=True)

print("Sorting Dictionary by Key in Descending Order:-")

print(sorted_result)

 

#sort dictionary by value Ascending

a = sorted(data.items(), key=lambda x: x[1])

print("sort dictionary by value Ascending:-")

print(a)

 

#Sort dictionary by value descending

a = sorted(data.items(), key=lambda x: x[1], reverse=True)

print("#Sort dictionary by value descending")

print(a)