Skip to main content

DICTIONARY PRACTICE QUESTIONS - 13-11-24

 

DICTIONARY PRACTICE QUESTIONS

1. Create a dictionary with the Rollno, Name and marks of students and display the name of students, who have scored marks above 75.

Sol:

# Input the number of students

no_of_std = int(input("Enter number of students: "))

result = {}

# Loop to enter details of each student

for i in range(no_of_std):

    print("Enter Details of student No.", i + 1)

    roll_no = int(input("Roll No: "))           # Input Roll Number

    std_name = input("Student Name: ")          # Input Student Name

    marks = int(input("Marks: "))               # Input Marks

    result[roll_no] = [std_name, marks]         # Store details in dictionary

# Print the dictionary with all students' details

print(result)

# Display names of students who have got marks more than 75

print("Students who scored more than 75 marks are:")

for student in result:

    if result[student][1] > 75:                 # Check if marks > 75

        print(result[student][0])               # Print the student's name


2. Python program to convert a number entered by the user into its corresponding number in words Eg: 123  - one two three [NCERT]

SOL:

num = input("Enter any number: ")

numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\

 5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'}

result = ''

for ch in num:

     key = int(ch) #converts character to integer

     value = numberNames[key]

     result = result + ' ' + value

print("The number is:",num)

print("The numberName is:",result)

3. Write a menu-driven program to create a dictionary containing roll numbers as keys. The value part is a list with marks of 5 subjects, total marks, percentage, and grade. The grade is assigned based on the given criteria:

Grade Criteria:

  • > 90 → Grade A
  • >= 75 and < 90 → Grade B
  • < 75 → Grade C
SOL:

# -*- coding: utf-8 -*-
"""
Created on Tue Nov 12 09:47:02 2024

@author: Kirti Hora
"""

stud = {}  # Dictionary to store student details
n = int(input("Enter no. of students: "))

# Loop to enter student details
for i in range(n):
    dets = []  # List to store details of each student
    
    # Input student roll number
    rno = int(input("Enter roll no: "))
    
    # Input student name
    name = input("Enter name: ")
    dets.append(name)
    
    # Input 5 marks
    for m in range(1,6):
        marks = float(input("Enter marks for subject:"))
        dets.append(marks)
    
    # Calculating total and percentage
    tot = sum(dets[1:6])  # Sum of marks (index 1 to 5)
    percentage = (tot / 500) * 100
    
    # Adding total and percentage to the details list
    dets.append(tot)
    dets.append(percentage)
    
    
    if percentage >= 90:
        grade = "A"
    elif percentage >= 75:
        grade = "B"
    else:
        grade = "C"
    
    # Adding grade to the details list
    dets.append(grade)
    
    # Storing the student details in the dictionary with roll number as the key
    stud[rno] = dets

# Output the final student dictionary
print("\nStudent Details:")
for roll_no, details in stud.items():
     print("Roll No:",roll_no , "Details",details)


Q4.Write a program to input your friends’ names and their Phone Numbers and store them in the dictionary as the key-value pair. Perform the following operations on the dictionary: 
a) Display the name and phone number of all your friends 
b) Add a new key-value pair in this dictionary and display the modified dictionary 
c) Delete a particular friend from the dictionary 
d) Modify the phone number of an existing friend 
e) Check if a friend is present in the dictionary or not 
f) Display the dictionary in sorted order of names

Sol:
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 13 08:16:26 2024

@author: Kirti Hora
"""
dic = {}

while True:
    print("1. Add New Contact")
    print("2. Modify Phone Number of Contact")
    print("3. Delete a Friend's contact")
    print("4. Display all entries")
    print("5. Check if a friend is present or not")
    print("6. Display in sorted order of names")
    print("7. Exit")
    
    inp = int(input("Enter your choice (1-7): "))

    # Adding a contact
    if inp == 1:
        name = input("Enter your friend's name: ")
        phonenumber = input("Enter your friend's contact number: ")
        dic[name] = phonenumber
        print("Contact Added\n")

    # Modifying a contact if the entered name is present in the dictionary
    elif inp == 2:
        name = input("Enter the name of the friend whose number is to be modified: ")
        if name in dic:
            phonenumber = input("Enter the new contact number: ")
            dic[name] = phonenumber
            print("Contact Modified\n")
        else:
            print("This friend's name is not present in the contact list\n")

    # Deleting a contact if the entered name is present in the dictionary
    elif inp == 3:
        name = input("Enter the name of the friend whose contact is to be deleted: ")
        if name in dic:
            del dic[name]
            print("Contact Deleted\n")
        else:
            print("This friend's name is not present in the contact list\n")

    # Displaying all entries in the dictionary
    elif inp == 4:
        print("All entries in the contact list:")
        if dic:
            for name in dic:
                print(name, "\t\t", dic[name])
        else:
            print("No contacts available.")
        print("\n")

    # Searching a friend's name in the dictionary
    elif inp == 5:
        name = input("Enter the name of the friend to search: ")
        if name in dic:
            print("The friend", name, "is present in the list with contact number:", dic[name], "\n")
        else:
            print("The friend", name, "is not present in the list\n")

    # Displaying the dictionary in sorted order of the names
    elif inp == 6:
        print("Name\t\t\tContact Number")
        for name in sorted(dic.keys()):
            print(name, "\t\t\t", dic[name])
        print("\n")

    # Exit the while loop if user enters 7
    elif inp == 7:
        print("Exiting the program. Goodbye!")
        break

    # Displaying the invalid choice when any other values are entered
    else:
        print("Invalid Choice. Please try again\n")


Comments

Popular posts from this blog

GRADE XII - Python Connectivity with MySQL

  Python Connectivity with MySQL In real-life applications, the data inputted by the user and processed by the application needs to be saved permanently, so that it can be used for future manipulation. Usually, input and output data is displayed during execution but not stored, as it resides in main memory , which is temporary — i.e., it gets erased once the application is closed. This limitation can be overcome by sending the data to be stored in a database , which is made accessible to the user through a Front-End interface . Key Concepts Database A database is an organized collection of data that is stored and accessed electronically from a computer system. DBMS (Database Management System) A DBMS is software that interacts with end-users, applications, and the database to capture and analyze data. Front-End The Front-End is the user interface of the application, responsible for input/output interaction with the user. Back-End The Back-End refe...

GRADE XII - CSV FILE

CSV FILE (COMMA SEPERATED VALUE) CSV NOTES LINK :  CSV NOTES - CLICK HERE Writing data to a CSV file involves the following steps: Import the csv module Open the CSV file in write mode ( "w" ) using open() Create the writer object Write the data into the file using the writer object Close the file using close() writerow() Method This method is used to write a single row to a CSV file. It takes a sequence (list or tuple) as its parameter, and writes the items as a comma-separated line in the file. You do not need to add a newline character (\n) — it automatically places the end-of-line marker.     EXAMPLE 1: import csv  # Importing the csv module # CSV file opened using relative path csv_fobj = open("emp.csv", "w")   # Writer object created wtr_obj = csv.writer(csv_fobj) # Record with field heading is written wtr_obj.writerow(["Empno", "Name", "Salary"]) # Records with data are...