Python Tutorial: Dictionary Exercises

Wednesday, 12 August 2020

Dictionary Exercises

 Dictionary Exercises

Q1. Accept customer name and phone. Search name of customer and print phone number of that name.

Answer :

Cphone=dict() #create empty dictionary

ch='y'

print("Enter customer details ")

while (ch=='Y' or ch=='y'):

    name=input("Enter the customer name :")

    phone=input("Enter phone number :")

    Cphone[name]=phone

    ch=input("Add more customer <y/n>").upper()

    if(ch=='n' or ch=='N'):

        break

SearchName=input("Enter name of customer to be find :")

flag=0

Ckeys=Cphone.keys()

for Cname in Ckeys:

    if(Cname==SearchName):

        flag=1

        break

if(flag==1):

    print("Phone no. of ",SearchName, "is ",Cphone[Cname])

else:

    print("Record not found")

print("\n Display All Record")

for c in Cphone:

    print(c,"\t:",Cphone[c])

 

    


Q2. Write a python program to input names of ‘n’ employees and their basic salary and calculate house rent and conveyance allowance 23% and 25% of basic salary respectively. Also Calculate total salary of each employee and display.

Answer :

# input value from keyboard to make dictionary

n=int(input("How many employee record to be entered :"))

Employee={} # empty dictionary

for i in range(n):

    ename=input("Name of the Employee :")

    sal=int(input("Enter the salary :"))

    hra=sal*23//100 # calculate house rent allowance

    ca=sal*25//100 # calculate conveyance allowance

    Employee[ename]=[sal,hra,ca] #add dictionary 

print("\nWihtout tabular form Show Dictionary")

print(Employee)

l=Employee.keys()

print("Print output in tabular form")

print("*"*50)

print("Name\tSalary House rent Conveyance Net Salary")

print("*"*50)   

print()

for e in l:

    salary=0

    z=Employee[e]

    ln=len(z)

    print(e,end="\t")

    for j in range(ln):

        print(z[j],end="\t")

        salary+=z[j]

    print(salary)    

    print()


Q3. Write a program that uses a dictionary that contains ten user and passwords. The program should ask the user to enter their usernames and passwords. If the username is not in the dictionary, the program should indicate that the person is not valid a valid user of the system. If the username is in the dictionary, but the user does not enter the right password, the program should say the password is invalid. If the password is correct, then the user program should tell the user that are now logged in the system.

 Answer :

Users={}

print("Enter user name and password ")

for i in range(5):

    print("Enter user ",i+1, " name ",end=": ")

    user=input()

    print("Enter password : ")

    passwd=input()

    Users[user]=passwd

# enter user and password

user=input("Enter user login")

pwd=input("Enter user password ")

if(user not in users.keys()):

    print("Invalid user name ")

elif(pwd not in users.values()):

    print("Invalid password ")

elif  (user in users.keys() and pwd in users.values()):

    print("logged")

else:

    print("not logged")


 

OR

Users=eval(input("Create dictionary enter user and password within {} \n"))

user=input("\nEnter user name for login system : ")

pwd=input("Enter user password : ")

if(user not in Users.keys()):

    print("Invalid user name ")

elif(pwd not in Users.values()):

    print("The user does not enter the right password. ")

elif  (user in Users.keys() and pwd in Users.values()):

    print("The user that are now logged in the system. ")

else:

    print("Not logged in the system")

Q4. Write a python program to input names of ‘n’ employees and their basic salary and calculate house rent and conveyance allowance 23% and 25% of basic salary respectively. Also Calculate total salary of each employee and display.

Answer :

# input value from keyboard to make dictionary

n=int(input("How many employee record to be entered :"))

Employee={} # empty dictionary

for i in range(n):

    ename=input("Name of the Employee :")

    sal=int(input("Enter the salary :"))

    hra=sal*23//100 # calculate house rent allowance

    ca=sal*25//100 # calculate conveyance allowance

    Employee[ename]=[sal,hra,ca] #add dictionary

print("\nWihtout tabular form Show Dictionary")

print(Employee)

l=Employee.keys()

print("Print output in tabular form")

print("*"*50)

print("Name\tSalary House rent Conveyance Net Salary")

print("*"*50)

print()

for e in l:

    salary=0

    z=Employee[e]

    ln=len(z)

    print(e,end="\t")

    for j in range(ln):

        print(z[j],end="\t")

        salary+=z[j]

    print(salary)

    print()

 

Q5. Write a Python program to input ‘n’ classes and names of their class teachers to store it in a dictionary and display same. Also accept a particular class from the user and display the name of the class teacher.

Answer:

ClassInfo=dict()

ch='y'

print("Enter Class and Class Teacher name details ")

while (ch=='Y' or ch=='y'):

    clas=input("Enter the Class in Roman number  :")

    name=input("Enter Class teacher name :")

    ClassInfo[clas]=name

    ch=input("Add more customer <y/n>").upper()

    if(ch=='n' or ch=='N'):

        break                                           # Terminate The Loop

print("\n Display All Record")

for c in ClassInfo:

    print(c,"\t:",ClassInfo[c])

SearchClass=input("\nEnter Class  :")

flag=False                                            #Boolean Variable

Ckeys=ClassInfo.keys()

for C in Ckeys:

    if(C==SearchClass):

        flag=True

        break

if(flag):                                 # if flag is true

    print("Phone no. of\"",SearchClass, " \"is \"",ClassInfo[C],"\"")

else:

    print("Record not found")

Q6. Write a python program to input names of ‘n’ customers and their details like items bought, cost and phone number, store it in a dictionary and display all the details in a tabular form.

Answer :

# input value from keyboard to make dictionary

n=int(input("How many Customer record to be entered :"))

Customer={} # empty dictionary

for i in range(n):

    print("Record ",i+1," Entry ->")

    custName=input("Name of the Customer :")

    bought=int(input("Enter number of items bought :"))

    cost=int(input("Enter number of items cost :"))

    contact=int(input("Enter customer contact :"))

    Customer[custName]=[bought,cost,contact] #add list into dictionary

print("\nWihtout tabular form Show Dictionary")

print(Customer)

custKeys=Customer.keys()

print("\nPrint output in tabular form")

print("*"*50)

print("Name\tBought\tCost\tContact")

print("*"*50)

for e in custKeys:

    z=Customer[e]

    ln=len(z)                                                                          # calculate length

    print(e,end="\t")

    for j in range(ln):

        print(z[j],end="\t")

    print()

 

Q. Write a python program to input names of ‘n’ employees and their basic salary and calculate house rent and conveyance allowance 23% and 25% of basic salary respectively. Also Calculate total salary of each employee and display. Make an employee dictionary menu, where can be add, delete, update and show all record.

 

MAIN MENU

    1.        Add element into dictionary

    2.        Delete elements from dictionary

    3.        Update dictionary element

    4.        Show dictionary element

    5.        Quit

    Answer :

                Employee=dict() #empty dictionary/array

opt=0

while(True):

    print()

    print('MAIN MENU')

    print('------------')

    print("1.           Add element into dictionary")

    print("2.           Delete elements from dictionary")

    print("3.           Update dictionary element")

    print("4.           Show dictionary element")

    print("5.           Quit")

    print("-----------")

    opt=int(input("Enter your option "))

    print()

    if(opt==1):

        ctr=1

        ch='Y'

        while(ch=='Y' or ch=='y'):

            print("Record ",ctr," Entry ->")

            ename=input("Name of the Employee :")

            sal=int(input("Enter the salary :"))

            hra=sal*23//100 # calculate house rent allowance

            ca=sal*25//100 # calculate conveyance allowance

            Employee[ename]=[sal,hra,ca] #add dictionary

            ch=input("Do you want to add more record (Y/N)...").upper()

            ctr+=1

            if(ch=='N' or ch=='n'):

                break

    elif(opt==2):                               # for delete

        key=input("Enter the key for delete :")

        element = Employee.pop(key)

        print("Deleted element :",element)

    elif(opt==3):                               #for update/edit

        temp={}                                 #empty dictionary

        SearchName=input("Name of the Employee :") # Search key in dictionary

        flag=False                              # boolean variable

        Ckeys=Employee.keys()

        for Ename in Ckeys:

            if(Ename==SearchName):              #compare variable

                flag=True

                break

        if(flag):                               # here flag variable is True

            sal=int(input("Enter the salary :"))

            hra=sal*23//100                     # calculate house rent allowance

            ca=sal*25//100                      # calculate conveyance allowance

            temp[SearchName]=[sal,hra,ca]            #create temp dictionary

            Employee.update(temp)

            print("Updated Dictionary.")

        else:

            print("Record not found")

    elif(opt==4):

        l=Employee.keys()

        print("Print output in tabular form")

        print("*"*50)

        print("Name\tSalary House rent Conveyance Net Salary")

        print("*"*50)

        for e in l:

            salary=0

            z=Employee[e]

            ln=len(z)

            print(e,end="\t")

            for j in range(ln):

                print(z[j],end="\t")

                salary+=z[j]

            print(salary)

    elif(opt==5):

        break

    else:

        print('Wrong option, try again')



No comments:

Post a Comment