You are on page 1of 3

MCAE08 – Programming with Python

Topic – Dictionary

Develop the scripts for the exercises given in the class and execute. Later continue with the
below exercises.
1. Develop a script to create a Phone book which has name and number using dictionary.
Perform the following operations on dictionary,
a. Adding entries to phone book.
b. Deleting entries from phone book.
c. Searching an entry in phone book.
d. Sort the elements of the phone book based on the names in ascending order.

phone_book = []
while(True):
ch = input("Specify operation to perform: view | add | delete | search | sort | exit \n>>")
if ch == 'exit' : break

if ch == "add":
phone_book.append({"name" : input("Enter name: "), "phone_no" : input("Enter
phone: ")})
print("\n")

if ch == "delete":
name = input("Enter the name you want to delete from the phone book \n")
for index, i in enumerate(phone_book):
if name == i['name']:
del phone_book[index]
print(i["name"] + " has been deleted from the phone book")

if ch == "search":
search = input("Enter the name that you want to search in the phone book \n")
for i in phone_book:
if search == i["name"]:
print("Found: {} | {} \n".format(i["name"], i["phone_no"]))

if ch == "view":
for index, i in enumerate(phone_book):
print("{}: {} | {} \n".format(index, i["name"], i["phone_no"]))
print("--------------")
print(phone_book)

if ch == "sort":
lst = []
for i in phone_book:
lst.append(i["name"])
lst.sort()
temp_phonebook = []
for name in lst:
for index, i in enumerate(phone_book):
if name == i["name"]:
temp_phonebook.append(phone_book[index])
phone_book = temp_phonebook

print(temp_phonebook)

2. Demonstrate the usage update( ) function to update one dictionary with another dictionary.

3. Analyze the code snippets given below and evaluate which code is more efficient when
execution time is considered as deciding factor.
Consider the following dictionary,
systems = {"mac": 1, "windows": 5, "linux": 1}
a. i = 0
v=0
x=0
while i < 10000000:
x = systems.get("windows", -1)
if x != -1:
v=x
i=i+1
b. i = 0
v=0
while i < 10000000:
if "windows" in systems:
v = systems["windows"]
i=i+1
To get the time value to calculate the execution time use the code below,
Import statement - import time, to get system time use time.time( ) function

4. Develop a script to count the occurrences of letters in a given string. this formula :

5. Analyze the given code snippet and comment on output.

num = int(input(“Enter a number less than 4”))


print({1:”One”,
2:”Two”,
3:”Three”,
4:”Four”}.get(num,”bad number”))
=>
enter a number less than 4 3
Three
enter a number less than 410
bad number

6. Develop a script to read user input until user enters “quit”. Arrange the words in
alphabetical order with line numbers where the words have occurred.

Ex: If user enters –


It was the best time
It was the worst time
Quit
Output should be,
best : [1]
It : [1, 2]
the : [1, 2]
time : [1, 2]
was : [1, 2]
worst : [2]

You might also like