Monday, 24 January 2022

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

Slip 29 Q 2

CODE :


dict1 = {}
n=int (input('Enter a number or pair in dict :'))
for i in range(n):
    key=input('enter {0} key :'.format(i+1))
    value=input('enter value of {}:'.format(key))
    dict1[key]=value
   
sorted_result = dict(sorted(dict1.items()))
print("\nSorting key in alphabetically ascending order:-")
print(sorted_result)

sorted_result = dict(sorted(dict1.items(), reverse=True))
print("\nSorting Dictionary by Key in Descending Order:-")
print(sorted_result)


a = dict(sorted(dict1.items(), key=lambda x: x[1]))
print("\nsort dictionary by value Ascending:-")
print(a)

a = dict(sorted(dict1.items(), key=lambda x: x[1], reverse=True))
print("\nSort dictionary by value descending:-")
print(a)

OUTPUT:



No comments:

Post a Comment

Write a Java program to display given extension files from a specific directory on server machine.

 DOWNLOAD     SLIP14Q2 /** * STEPS TO RUN CODE * Step 01 compile the code * Step 02 run the code * Step 03 give a file directory locatio...