Python Program to sort (by Ascending or Descending) a dictionary by key or by value.

#Python Program to sort (by Ascending or Descending) a dictionary by key or by value.

dict1={}
list0=[]
list1=[]


def createDict():
    for i in range(N):
        key=input("Enter key for item %d:"% i)
        list0.append(key)

    print("\n")

    for i in range(N):
        value=input("Enter value for key "+list0[i]+":")
        list1.append(value)

    for i in range(N):
        dict1[list0[i]]=list1[i]

    print("\nEntered dictionary is:")
    print(dict1)


def sortByKey():
    A = int(input("Enter 1 to sort in Ascending order or enter 0 to sort in descending order:"))
    if A == 1:
        print("\nDictionary sorted by key in Ascending order is:")
        DicAsc = sorted(dict1.items(), key = lambda t: t[0])
        print (DicAsc)
    elif A == 0:
        print("\nDictionary sorted by key in Descending order is:")
        DicDesc = sorted(dict1.items(), key = lambda t: t[0], reverse = True)
        print (DicDesc)
    else:
        print("\nYou have entered wrong choice try again:")
        exit

def sortByValue():
    P = int(input("Enter 1 to sort in Ascending order or enter 0 to sort in descending order:"))
    if P == 1:
        print("\nDictionary sorted by value in Ascending order is:")
        DicAsc = sorted(dict1.items(), key = lambda t : t[1])
        print(DicAsc)
    elif P == 0:
        print("\nDictionary sorted by value in descending order is:")
        DicDesc = sorted(dict1.items(), key = lambda t: t[1], reverse = True)
        print(DicDesc)
    else:
        print("\nYou have entered wrong choice try again:")
        exit


N=int(input("Enter Number of items in dictionary:"))
createDict()

S = int(input("\nEnter 1 to sort by key or 0 to sort by value:"))
if S == 1:
    sortByKey()
elif S == 0:
    sortByValue()
else:
    print("\nYou have entered wrong choice try again later:")
    exit

Comments

Popular posts from this blog

Python program to calculate age and year when user will be 100 years old

Python program to print numbers less than 5 from the list.